0% found this document useful (0 votes)
15 views31 pages

Python Programs for Common Algorithms

The document contains a list of 24 Python programming experiments covering various topics such as algorithms for prime numbers, factorials, Fibonacci sequences, matrix operations, and file handling. Each experiment includes code snippets and explanations for tasks like generating perfect numbers, computing GCD and LCM, and manipulating strings and files. The document serves as a practical guide for learning Python through hands-on coding exercises.

Uploaded by

JNV Rajnandgaon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views31 pages

Python Programs for Common Algorithms

The document contains a list of 24 Python programming experiments covering various topics such as algorithms for prime numbers, factorials, Fibonacci sequences, matrix operations, and file handling. Each experiment includes code snippets and explanations for tasks like generating perfect numbers, computing GCD and LCM, and manipulating strings and files. The document serves as a practical guide for learning Python through hands-on coding exercises.

Uploaded by

JNV Rajnandgaon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EXPERIMENTS LIST – XII (CS - 083)

1.

# Python program to print all primes up to n using Sieve of Eratosthenes

def SieveOfEratosthenes(n):

# Create a boolean array "prime[0..n]" and initialize

# all entries as true. A value in prime[i] will

# finally be false if i is Not a prime, else true.

prime = [True for i in range(n + 1)]

p=2

while (p * p <= n):

# If prime[p] is not changed, then it is a prime

if (prime[p] == True):

# Update all multiples of p

for i in range(p * 2, n + 1, p):

prime[i] = False

p += 1

prime[0]= False

prime[1]= False

# Print all prime numbers

for p in range(n + 1):


if prime[p]:

print (p, end=' ')

# Driver program

n = 30

print("Following are the prime numbers up to", n)

SieveOfEratosthenes(n)

2.

# Program to generate factorial of all elements in an array/list

def factorialList(l):

fact_l = [] # Empty list initially

for n in l:

f=1

for i in range(1, n+1):

f *= i

fact_l.append(f)

return fact_l

# Driver program

l = [5, 2, 4, 6]

fact_l = factorialList(l)

print('Following is the list of factorials: ')


for i in fact_l:

print(i, end=' ')

3.

# Program to display the Fibonacci sequence up to n-th term

def fibonacci(n):

# first two terms

a, b = 0, 1

count = 0

# check if the number of terms is valid

if n <= 0:

print("Please enter a positive integer")

elif n == 1:

print("Fibonacci sequence upto",n,":")

print(a)

else:

print("Fibonacci sequence:")

while count < n:

print(a, end=' ')

c=a+b

# update values

a=b
b=c

count += 1

n = int(input("How many terms? "))

fibonacci(n)

4.

# Program to generate perfect numbers in an Interval

def perfectNumbers(lim1, lim2):

for n in range(lim1, lim2+1):

sum=0

for i in range(1,n):

if n%i==0:

sum+=i

if sum==n:

print(n, end=' ')

lim1=int(input('Enter min range: '))

lim2=int(input('Enter max range: '))

print('Perfect numbers:')

perfectNumbers(lim1, lim2)
5.

# Program to generate armstrong numbers in an Interval

def armstrongNumbers(lim1, lim2):

for n in range(lim1, lim2+1):

m=n

sum=0

while n>0:

r=n%10

sum+=r**3

n=n//10

if sum==m:

print(m, end=' ')

lim1=int(input('Enter min range: '))

lim2=int(input('Enter max range: '))

print('Armstrong numbers:')

armstrongNumbers(lim1, lim2)

6.

# Program to find the sum of Harshad numbers in an interval


def isHarshad(n):

sum = 0

m=n

while m > 0:

sum = sum + m % 10

m = m // 10

# Return True if sum of digits divides n

if n % sum == 0:

return True

def sumOfHarshadNumbers(lim1, lim2):

sum = 0

for n in range(lim1, lim2+1):

if isHarshad(n):

sum += n

return sum

# Driver code

lim1=int(input('Enter min range: '))

lim2=int(input('Enter max range: '))

print('Sum of Harshad numbers in this range:', sumOfHarshadNumbers(lim1, lim2))

7.
# Program to display x raised to power y using anonymous (lambda) function

import math

mypow = lambda x,y: [Link](x, y)

x=int(input('Enter value for base: '))

y=int(input('Enter value for exponent: '))

result=mypow(x, y)

print('Using Anonymous function (Lambda)')

print('The base raised to power exponent:', result)

8.

# Program to find GCD/HCF and LCM using Euclidian algorithm

# This function computes GCD

def compute_gcd(x, y):

while(y):

x, y = y, x % y

return x

# This function computes LCM

def compute_lcm(x, y):

lcm = (x*y)//compute_gcd(x,y)
return lcm

num1 = int(input('Enter first number: '))

num2 = int(input('Enter second number: '))

print("The GCD is", compute_gcd(num1, num2))

print("The LCM is", compute_lcm(num1, num2))

9.

# Program to add two Matrices

def addMatrices(A, B):

C = [[0,0,0],

[0,0,0],

[0,0,0]]

# iterate through rows

for i in range(len(A)):

# iterate through columns

for j in range(len(A[0])):

C[i][j] = A[i][j] + B[i][j]

print('Resultant matrix:')

for row in C:
print(row)

A = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

B = [[5,8,1],

[6,7,3],

[4,5,9]]

print('Matrix Addition')

addMatrices(A, B)

10.

# Program to obtain transpose of a Matrix

def matrixTranspose(A):

AT = [[0,0,0],

[0,0,0],

[0,0,0]]

# iterate through rows

for i in range(len(A)):
# iterate through columns

for j in range(len(A[0])):

AT[i][j] = A[j][i]

print('Resultant matrix:')

for row in AT:

print(row)

A = [[12,7,3],

[4,5,6],

[7,8,9]]

print('Matrix Transpose')

matrixTranspose(A)

11.

# Program to multiply two Matrices

def multiplyMatrices(A, B):

C = [[0 for j in range(len(B[0]))] for i in range(len(A))] # List comprehension

# iterate through rows - A

for i in range(len(A)):

# iterate through columns - B


for j in range(len(B[0])):

# iterate through columns - A OR rows - B

for k in range(len(A[0])):

C[i][j] += A[i][k] * B[k][j]

print('Resultant matrix:')

for row in C:

print(row)

A = [[2,3,1],

[6,2,7],

[5,8,3]]

B = [[6,5,4],

[3,7,2],

[8,1,9]]

print('Matrix Multiplication')

multiplyMatrices(A, B)

12,

# Program to remove punctuations from a string

def removePunctuation(my_str):
# punctuation marks

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# traverse the given string and remove any punctuation

without_punct = ""

for char in my_str:

if char not in punctuations:

without_punct = without_punct + char

# Print string without punctuation

string = without_punct

print(string)

# Driver program

my_str = "CS@@??##?$ at JNV^^..#$% Dongargarh 491445%$^$%&, (C.G.)"

removePunctuation(my_str)

13.

# Program to sort words lexicographically using Bubble sort

def bubble_sort(arr):

n=len(arr)

for i in range (n):


for j in range(n-i-1):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

return arr

# Driver code

arr=['Orange','banana','pomegranate','guava','apple']

print('Bubble Sort')

print('List before sort:', arr)

print('List after sort:',bubble_sort(arr))

14.

# Program to perform Insertion sort

def insertion_sort(arr):

n=len(arr)

for i in range (1, n):

key = arr[i]

j=i-1

while key <arr[j] and j>=0:

arr[j+1]=arr[j]

j=j-1
arr[j+1]=key

return arr

# Driver code

arr=[12,3,45,6,78,9,72]

print('Insertion Sort')

print('List before sort:', arr)

print('List after sort:',insertion_sort(arr))

15.

# Program to count frequency of each vowel in a string using dictionary

def count_vowel_occurrence(string):

vowels = ['a','e','i','o','u']

my_dictionary = {}

for char in string:

if [Link]() in vowels:

my_dictionary[char] = my_dictionary.get(char,0) + 1

for k, v in my_dictionary.items():

print(k, 'appears', v, 'time(s)')


string = 'JNV Dongargarh, Distt. Rajnandgaon'

count_vowel_occurrence(string)

16.

# Program to find the size (resolution) of an image

'''

# DON’T USE THIS CODE. USE THE NEXT ONE.

def jpeg_resolution(filename):

# Open image file for reading in binary mode

with open(filename,'rb') as file:

# Height of image (in 2 bytes) is at 164th position

[Link](163)

# Reading the 2 bytes

a = [Link](2)

# Calculating height

height = (a[0] << 8) + a[1]

# Width is next 2 bytes

a = [Link](2)

# Calculating width
width = (a[0] << 8) + a[1]

print('The resolution of the image is',width,'x',height)

jpeg_resolution('[Link]')

'''

# Using PIL

from PIL import Image

# loading the image

img = [Link]('[Link]')

# Fetching and displaying the dimensions

width, height = [Link]

print('Resolution:',str(width) + 'x' + str(height))

# Using OpenCV

import cv2

# Loading the image

img = [Link]('[Link]')
# Fetching and displaying the dimensions

width = [Link][1]

height = [Link][0]

print(str(width) + 'x' + str(height))

17.

# Program to find hash value of a file

import hashlib

def compute_hash(filename):

BUF_SIZE = 32768 # Read file in 32kb chunks

md5 = hashlib.md5()

sha1 = hashlib.sha1()

with open(filename, "rb") as file:

while True:

data = [Link](BUF_SIZE)

if not data:

break

[Link](data)

[Link](data)
print("MD5:",[Link]())

print("SHA1:",[Link]())

compute_hash("[Link]")

18.

# Read a text file line by line and display each word separated by a #

file=open('[Link]','r')

# Fetching and traversing through lines

lines=[Link]()

for line in lines:

words=[Link]() # Split the line into list of words

for word in words: # Traverse each word

print(word, end='#') # Prints each word suffixed with #

[Link]()

19.

# Read a text file and display the number of vowels/ consonants/

# uppercase/ lowercase characters in the file


vowel_list = ['a','e','i','o','u']

record = {}

with open('[Link]','r') as file:

# Fetching content of file

text = [Link]()

for char in text:

if [Link]():

record['u'] = [Link]('u',0) + 1

elif [Link]():

record['l'] = [Link]('l',0) + 1

if [Link]() in vowel_list:

record['v'] = [Link]('v',0) + 1

else:

record['c'] = [Link]('c',0) + 1

print(record)

20.

# Create a binary file with name and roll number.

# Search for a given roll number and display the name,

# if not found display appropriate message


import pickle

def writeData():

student1 = {'name':'Sanjay', 'rollNo':'1'}

student2 = {'name':'Anil', 'rollNo':'2'}

record = {}

record['stud1'] = student1

record['stud2'] = student2

with open('dataFile','wb') as file:

[Link](record, file)

print('Record is stored successfully\n')

def readName():

rollNo = input('Enter Roll no. to search: ')

found = False

with open('dataFile','rb') as file:

info = [Link](file)

for key in info:

if info[key]['rollNo'] == rollNo:

print(info[key]['name'])

found = True

if not found:
print('The Roll number does not exist!')

# Driver code

writeData()

readName()

21.

# Create a binary file with roll number, name and marks.

# Input a roll number and update the marks

import pickle

def writeData():

student1 = {'rollNo':'1','name':'Sanjay','mark':85}

student2 = {'rollNo':'2','name':'Anil','mark':92}

record = {}

record['stud1'] = student1

record['stud2'] = student2

with open('dataFile','wb') as file:

[Link](record, file)

print('Record is stored successfully\n')


def updateMark():

rollNo = input('Enter Roll no. to update mark: ')

with open('dataFile','rb') as file:

info = [Link](file)

for key in info:

if info[key]['rollNo'] == rollNo:

print(info[key]['name'],'scored',info[key]['mark'])

new_mark = int(input('Enter new mark: '))

info[key]['mark']=new_mark

with open('dataFile','wb') as file:

[Link](info, file)

print('Mark is updated')

def readData():

rollNo = input('Enter Roll no. to search: ')

with open('dataFile','rb') as file:

info = [Link](file)

for key in info:

if info[key]['rollNo'] == rollNo:

print(info[key]['name'],'scored',info[key]['mark'])

# Driver code

writeData()

updateMark()
readData()

22.

# Remove from all lines the character 'a' in a file and write it to another file

with open('[Link]','r') as file_r:

with open('[Link]','w') as file_w:

lines = file_r.readlines()

for l in lines:

if 'a' in l:

l=[Link]('a','')

file_w.write(l)

print('Required operation is successful. Please check file content.')

23.

# Write a random number generator that generates random numbers between 1 and 6 (simulates a
dice)

import random

def diceRoll():

my_list = []

ctr = 0
while ctr < 6:

num = [Link](1, 6)

my_list.append(num)

ctr += 1

if ctr >= 6:

pass

else:

return my_list

play = 1

while play==1:

play = int(input('Press 1 to play roll the dice: '))

print(diceRoll())

24.

# Write a Python program to implement a stack using a list data-structure

# Creating a stack

def create_stack():

stack = []

return stack

# Creating an empty stack

def check_empty(stack):
return len(stack) == 0

# Adding items into the stack

def push(stack, item):

[Link](item)

print("pushed item: " + item)

# Removing an element from the stack

def pop(stack):

if check_empty(stack):

return "stack is empty"

return [Link]()

# Main section

stack = create_stack()

push(stack, "1")

push(stack, "2")

push(stack, str(3))

push(stack, str(4))

print("popped item: " + pop(stack))

print("stack after popping an element:", stack)

25.

# Write a Python program to implement a queue


# Implementing Queue using deque

from collections import deque

queue = deque(["Apple", "Banana", "Orange", "Mango"])

print(queue)

[Link]("Grape")

print(queue)

[Link]("Litchi")

print(queue)

print([Link]())

print([Link]())

print(queue)

26.

# Take a sample of ten phishing e-mails (or any text file) and find most commonly occurring word(s)

from collections import Counter

file=open('phishing_data.txt','r') # this file contains phishing emails

dataset=[Link]()

n=10 # top 10 most occurring

split_it=[Link]()

count=Counter(split_it)

most_occur=count.most_common(n)
print('The following words are most occurring:')

print(most_occur)

[Link]()

27.

# Program to insert record into MySQL database

import MySQLdb

# Open database connection

db = [Link]("localhost","root","","mydb" )

# prepare a cursor object using cursor() method

cursor = [Link]()

# Prepare SQL query to INSERT a record into the database.

sql = "INSERT INTO LOAN VALUES ('L4','B4',10000)"

try:

# Execute the SQL command

[Link](sql)

# Commit your changes in the database

[Link]()

except:
# Rollback in case there is any error

[Link]()

# disconnect from server

[Link]()

print("Record inserted")

28.

# Program to update record in MySQL database

import MySQLdb

# Open database connection

db = [Link]("localhost","root","","mydb" )

# prepare a cursor object using cursor() method

cursor = [Link]()

# Prepare SQL query to INSERT a record into the database.

sql = "UPDATE LOAN SET AMOUNT=15000 WHERE LOANNO='L4'"

try:

# Execute the SQL command

[Link](sql)
# Commit your changes in the database

[Link]()

except:

# Rollback in case there is any error

[Link]()

# disconnect from server

[Link]()

print("Record updated")

29.

# Program to delete record from MySQL database

import MySQLdb

# Open database connection

db = [Link]("localhost","root","","mydb" )

# prepare a cursor object using cursor() method

cursor = [Link]()

# Prepare SQL query to INSERT a record into the database.

sql = "DELETE FROM LOAN WHERE LOANNO='L4'"


try:

# Execute the SQL command

[Link](sql)

# Commit your changes in the database

[Link]()

except:

# Rollback in case there is any error

[Link]()

# disconnect from server

[Link]()

print("Record deleted")

30.

import MySQLdb

# Open database connection

#mydb = [Link](host="localhost", user="root", passwd="", database="mydb")

db = [Link](host="localhost",user="root",passwd="",database="mydb" )

# prepare a cursor object using cursor() method

cursor = [Link]()
#sql = "SELECT * FROM LOAN WHERE AMOUNT > '%d'" % (1000)

sql = "SELECT * FROM LOAN ORDER BY AMOUNT DESC"

try:

# Execute the SQL command

[Link](sql)

# Fetch all the rows

results = [Link]()

for row in results:

loan = row[0]

bank = row[1]

amount = row[2]

# Now print fetched result

print ("loan=%s,bank=%s,amount=%.2f" % \

(loan, bank, amount) )

except:

print ("Error: unable to fetch data")

# disconnect from server

[Link]()

You might also like