Practical
Of
Python Programming Lab
Submitted By:
Nitish(1222642)
Submitted To:
Er. Priyanka Sharma
AP (IT)
DepartmentofInformation Technology
Seth Jai Parkash Mukand Lal Institute of Engineering & Technology
AffiliatedtoKurukshetraUniversityKurukshetra
Nitish
1222642
INDEX
Sr. No. Objective Signature
1 WAP to compute the GCD of two numbers
2 WAP to find the square root of a number
3 WAP to find the Exponentiation (power of a
number)
4 WAP to find the maximum of a list of numbers
5(a) WAP for Linear search
5(b) WAP for Binary search
6(a) WAP for Selection sort
6(b) WAP for Insertion sort
7 WAP for Merge sort
8 WAP to find first n prime numbers
9 WAP to multiply matrices
10 WAP that take command line arguments (word
count)
11 WAP to find the most frequent words in a text read
from a file
12 WAP to simulate bouncing ball using Pygame
2
Nitish
1222642
Practical – 1
Aim:- WAP to compute the GCD of two numbers.
Algorithm:
1. Get two numbers from user
2. Define a function named computeGCD()
3. Find the smallest among the two inputs x and y
4. Perform the following step till smaller+1
Check if ((x % i == 0) and (y % i == 0)), then assign GCD=i
5. Print the value of gcd
Source Code:-
def computeGCD(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The GCD. of", num1,"and", num2,"is", computeGCD(num1, num2))
3
Nitish
1222642
Output:-
4
Nitish
1222642
Practical – 2
Aim:-WAP to find the square root of a number.
Algorithm:
1. Get a number from user
2. Use num ** 0.5
double asterisk (**) is defined as exponentiation operator
3. Print the value of suareroot
Source Code:-
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output:-
5
Nitish
1222642
Practical – 3
Aim:-WAP to find the Exponentiation (power of a number).
Algorithm:
1. Read the value of number and exponent
2. Set power = 1
3. Perform the following step till exponent + 1
for i in range(1, exponent + 1):
power = power * number
4. Print the result
Source Code:-
number = int(input(" Please Enter any Positive Integer : "))
exponent = int(input(" Please Enter Exponent Value : "))
power = 1
for i in range(1, exponent + 1):
power = power * number
print("The Result of {0} Power {1} = {2}".format(number, exponent, power))
Output:-
6
Nitish
1222642
Practical – 4
Aim:-WAP to find the maximum of a list of numbers.
Algorithm:
1. Create an empty list named l
2. Read the value of n
3. Read the elements of list until n
4. Assign l[0] as maxno
5. Repeat till len(l)
i. If l[i] >maxno then set maxno = l[i]
ii. Increment i by 1
iii. Repeat steps i-ii until i< n
9. Print the value of maximum number
Source Code:-
l=[]
n=int(input("enter the upper limit"))
for i in range(0,n):
a = int(input("enter the number"))
[Link](a)
maxno=l[0]
for i in range(0,len(l)):
if l[i] >maxno:
maxno = l[i]
print("The maximum number is %d"%maxno)
7
Nitish
1222642
Output:-
8
Nitish
1222642
Practical – 5(a)
Aim:-WAP for Linear search.
Algorithm:
1. Initialize list
2. Read element to be searched
3. Define a search function
4. Read the elements of list until n
if list[pos]==item return pos
5. Return -1 if item not found
Source Code:-
def search(arr, n, x):
for i in range (0, n):
if (arr[i] == x):
return i;
return -1;
arr = [ 2, 3, 4, 10, 40 ];
x = int(input('Enter a number to search: '))
n = len(arr);
result = search(arr, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result)
9
Nitish
1222642
Output:-
10
Nitish
1222642
Program – 5(b)
Aim:- WAP for binary search.
Algorithm:
1. Initialize list
2. Read element to be searched
3. Define a binarysearch function
4. Compare item with middle element
5. If item matches with middle element we return mid index
6. Else if item is greater than mid element, then item can only lie in right half subarray
after mid element. So we recur for right half
7. Else(item is smaller) recur for left half
Source Code:-
def binarySearch (arr, l, r, x):
if r >= l:
mid = (int)(l + (r - l)/2)
if (arr[mid] == x):
return mid
elif (arr[mid] > x):
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = int(input('Enter a number to search: '))
result = binarySearch(arr, 0, len(arr)-1, x)
11
Nitish
1222642
if(result != -1):
print("Element is present at index", result)
else:
print("Element is not present in array")
Output:
12
Nitish
1222642
Program – 6(a)
Aim:- WAP for Selection sort.
Algorithm:
1. Read list
2. Define a selection_sort function
3. Initialize min_pos=index
4. if arr[location] <arr[min_pos] then perform till length of list
5. Set min_pos=location
6. Swap arr[i] and arr[min_pos]
7. Print the sorted list
Source Code:-
def selection_sort(alist):
for i in range(0, len(alist) - 1):
min = i
for j in range(i + 1, len(alist)):
if alist[j] <alist[min]:
min = j
alist[i], alist[min] = alist[min], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
13
Nitish
1222642
Output :
14
Nitish
1222642
Program – 6(b)
Aim:- WAP for insertion sort.
Algorithm:
1. Read list
2. Define ainsertion_sort function
3. Initialize current value=alist[index] and position=index-1
4. While positon>=0 and alist[position]>currentvalueperform following till len(list)
5. Set alist[positon+1]=alist[position]
6. position= position-1
7. alist[position] = currentvalue
8. Print the sorted list
Source Code:-
def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j=i-1
while (j >= 0 and temp <alist[j]):
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)
15
Nitish
1222642
Output:
16
Nitish
1222642
Practical – 7
Aim:-WAP for Merge sort.
Algorithm:
1. Read list
2. Define a merge_sort function
3. Call mergesort(arr, l, r)
4. Find middle point to divide the array in two halves:
middle m = (l+r)/2
5. Call mergesort for first half
Call merge_sort(arr, l, m)
6. Call mergesort for second half
Call merge_sort(arr, m+1, r)
7. Merge the two halves sorted in step 5 and 6
8. Print the sorted list
Source Code:-
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
17
Nitish
1222642
i=0
j=0
k=l
while (i< n1 and j < n2):
if (L[i] <= R[j]):
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while (i< n1):
arr[k] = L[i]
i += 1
k += 1
while (j < n2):
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr,l,r):
if l < r:
m = (int)((l + ( r - 1)) / 2)
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
18
Nitish
1222642
arr = input('Enter the numbers: ').split()
arr = [int(x) for x in arr]
n = (int)(len(arr))
print ("Given array is")
for i in range(n):
print ("%d" %arr[i])
mergeSort(arr,0,n-1)
print ("\nSorted array is")
for i in range(n):
print ("%d" %arr[i])
Output:-
19
Nitish
1222642
Program – 8
Aim:- WAP to find first n prime numbers.
Algorithm:
1. Read upper limit r
2. for num in range(2, r+1) perform
3. Set k = 0
4. for i in range(2, a/2+1) perform
if num%i is 0 set k = k +1
5. if(k <=0 print num
Source Code:-
r = int(input("Enter upper limit: "))
for a in range(2, r + 1):
k=0
for i in range(2, a // 2 + 1):
if(a % i == 0):
k += 1
if(k <= 0):
print(a)
20
Nitish
1222642
Output:-
21
Nitish
1222642
Practical – 9
Aim:-WAP to multiply matrices.
Algorithm:
1. Define two matrices X and Y
2. Create a resultant matrix named result
3. for i in range(len(X)) perform
for j in range(len(Y[0]) perform
for k in range(len(Y[]) perform
result = result[i]+X[i][k]* Y[k][j]
4. for r in result, print the value of r
Source Code:-
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
22
Nitish
1222642
for r in result:
print(r)
Output:-
23
Nitish
1222642
Program – 10
Aim:- WAP that take command line arguments (word count).
Algorithm:
1. Add arguments to count arguments
2. Find program name using [Link][0]
3. Find arguments using [Link][1:]
4. Count words using len(arguments)
5. Print program name, arguments, count
Source Code:-
import sys
program_name = [Link][0]
arguments = [Link][1:]
count = len(arguments)
if (count < 2) :
print ("no arguments")
[Link] (1)
print("program_name: ", end='')
print(program_name)
print("arguments: ", end='')
print(arguments)
print("count: ", end='')
print(count)
24
Nitish
1222642
Output:
25
Nitish
1222642
Program – 11
Aim:- WAP to find the most frequent words in a text read from a file
Algorithm:
1. Read the filename
2. Open the file in read mode
3. Read each line from file to count the lowers and words
4. Read each line from the file to replace the punctuations
5. Print the words and counts
Source Code:-
def main():
filename = input("enter the filename: ").strip()
infile = open(filename, "r")
wordcounts = {}
for line in infile:
processLine([Link](), wordcounts)
pairs = list([Link]())
items=[[x,y] for (y,x) in pairs]
[Link]()
for i in range(len(items)-1,len(items)-11,-1):
print(items[i][1]+"\t"+str(items[i][0]))
def processLine(line,wordcounts):
line=replacePunctuations(line)
words=[Link]()
26
Nitish
1222642
for word in words:
if word in wordcounts:
wordcounts[word]+=1
else:
wordcounts[word]=1
def replacePunctuations(line):
for ch in line:
if ch in "~@#$%^&*()_-+=<>?/.,:;!{}[]''":
line=[Link](ch," ")
return line
main()
Output:
27
Nitish
1222642
Program – 12
Aim:- WAP to simulate bouncing ball using Pygame
Algorithm:
1. Import packages sys and pygame
2. Define the required variables
3. Define the screen space to display the bouncing balls in that space
Source Code:-
import sys
import pygame
[Link]()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = [Link].set_mode(size)
ball = [Link]('C:\\Users\\home\\Desktop//[Link]')
ballrect = ball.get_rect()
while 1:
for event in [Link]():
if [Link] == [Link]: [Link]()
ballrect = [Link](speed)
if [Link]< 0 or [Link]> width:
speed[0] = -speed[0]
28
Nitish
1222642
if [Link]< 0 or [Link]> height:
speed[1] = -speed[1]
[Link](black)
[Link](ball, ballrect)
[Link]()
Output:
29