21CS202 - Lab Manual
21CS202 - Lab Manual
0 0 42
Lab Manual
List of programs
1. Compute the GCD of two numbers.
2. Find the square root of a number (Newton’s method)
3. Exponentiation (power of a number)
4. Find the maximum of a list of numbers
5. Linear search and Binary search
6. Selection sort, Insertion sort
7. Merge sort
8. First n prime numbers
9. Multiply matrices
10. Programs that take command line arguments (word count)
11. Find the most frequent words in a text read from a file
12. Simulate elliptical orbits in Pygame
13. Simulate bouncing ball using Pygame
PLATFORM NEEDED
TOTAL: 60 PERIODS
1.Find the GCD of the numbers using fractions
import fractions
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
print("The GCD of the two numbers is",fractions.gcd(a,b))
OUTPUT
>>> runfile('C:/Users/admin/gcd.py', wdir='C:/Users/admin')
Enter the first number: 24
Enter the second number:64
The GCD of the two numbers is 8
>>>
Alternate Method
def computegcd(x, y):
# choose the smaller number
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
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
print("The G.C.D. of", n1,"and", n2,"is", computegcd(n1, n2))
2.Find the Newton’s square root
Method
x1,x2,x3,x4……xn iterations
CODE:
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
print(newtonSqrt(10, 3))
print(newtonSqrt(10, 5))
print(newtonSqrt(10, 10))
n=10
Howmany iterations 3 (first input)
n=10
Howmany iterations 5 (second input)
n=10
Howmany iterations 10 (third input)
Also use int(input()) method for getting n and how many
Alternative Method
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
n=int(input("enter n"))
howmany=int(input("enter howmany iterations"))
print(newtonSqrt(n,howmany))
OUTPUT
enter n 10
enter howmany iterations3
3.162319422150883
>>>
3.Find the Exponentiation
import math
x=int(input("enter x"))
y=int(input("enter y"))
print ('power',math.pow(x,y))
OUTPUT
>>> runfile('C:/Users/admin/p.py', wdir='C:/Users/admin')
enter x 5
enter y2
power 25.0
>>>
4.Finding the Maximum in list
n=int(input("enter n"))
alist=[]
for i in range(n):
alist.append(input("Enter %dth element: "%i))
largest=alist[0]
for large in alist:
if large > largest:
largest=large
print(largest)
OUTPUT
enter n 5
Enter 0th element: 12
Enter 1th element: 50
Enter 2th element: 4
Enter 3th element: 70
Enter 4th element: 25
70
Alternate Method
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Max value element : ", max(list1)
print "Max value element : ", max(list2)
OUTPUT
========================= RESTART: C:/Python27/mm.py ====================
Max value element : zara
Max value element : 700
>>>
5.a.Binary search
def binary_sort(sortedlist,n,x):
start = 0
end = n - 1
while(start <= end):
mid = (start + end)/2
if (x == sortedlist[mid]):
return mid
elif(x < sortedlist[mid]):
end = mid - 1
else:
start = mid + 1
return -1
n = input("Enter the size of the list: ")
sortedlist = []
for i in range(n):
sortedlist.append(input("Enter %dth element: "%i))
x = input("Enter the number to search: ")
position = binary_sort(sortedlist, n, x)
if(position != -1):
print("Entered number %d is present at position: %d"%(x,position))
else:
print("Entered number %d is not present in the list"%x)
OUTPUT
Enter the size of the list: 5
Enter 0th element: 2
Enter 1th element: 3
Enter 2th element: 6
Enter 3th element: 7
Enter 4th element: 8
Enter the number to search: 6
Entered number 6 is present at position: 2
>>>
5. b Linear search
n = input("Enter the size of the list: ")
list = []
for i in range(n):
list.append(input("Enter %dth element: "%i))
x = int(input("Enter number to search: "))
found = False
for i in range(len(list)):
if(list[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break
if(found == False):
print("%d is not in list"%x)
OUTPUT
Enter the size of the list: 5
Enter 0th element: 7
Enter 1th element: 8
Enter 2th element: 9
Enter 3th element: 5
Enter 4th element: 6
Enter number to search: 7
7 found at 0th position
>>>
6.a.Selection Sort
n = input("Enter the size of the list: ")
source = []
for i in range(n):
source.append(input("Enter %dth element: "%i))
for i in range(len(source)):
mini = min(source[i:]) #find minimum element
min_index = source[i:].index(mini) #find index of minimum element
source[i + min_index] = source[i] #replace element at min_index with first element
source[i] = mini #replace first element with min element
print source
OUTPUT
Enter the size of the list: 5
Enter 0th element: 4
Enter 1th element: 5
Enter 2th element: 8
Enter 3th element: 9
Enter 4th element: 7
[4, 5, 7, 8, 9]
>>>
6.b.Insertion Sort
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
n = input("Enter the size of the list: ")
n=int(n)
alist = [ ]
for i in range(n):
alist.append(input("Enter %dth element: "%i))
insertionSort(alist)
print(alist)
OUTPUT
Enter the size of the list: 5
Enter 0th element: 7
Enter 1th element: 8
Enter 2th element: 4
Enter 3th element: 3
Enter 4th element: 2
['2', '3', '4', '7', '8']
>>>
7. Merge Sort
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
alist[k]=lefthalf[i]
i=i+1
k=k+1
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = []
for i in range(n):
mergeSort(alist)
print(alist)
OUTPUT
Enter the size of the list: 6
Enter 0th element: 2
Enter 1th element: 8
Enter 2th element: 6
Enter 3th element: 5
Enter 4th element: 3
Enter 5th element: 1
Splitting ['2', '8', '6', '5', '3', '1']
Splitting ['2', '8', '6']
Splitting ['2']
Merging ['2']
Splitting ['8', '6']
Splitting ['8']
Merging ['8']
Splitting ['6']
Merging ['6']
Merging ['6', '8']
Merging ['2', '6', '8']
Splitting ['5', '3', '1']
Splitting ['5']
Merging ['5']
Splitting ['3', '1']
Splitting ['3']
Merging ['3']
Splitting ['1']
Merging ['1']
Merging ['1', '3']
Merging ['1', '3', '5']
Merging ['1', '2', '3', '5', '6', '8']
['1', '2', '3', '5', '6', '8']
>>>
8. Finding N prime numbers
i=1
x = int(input("Enter the number:"))
for k in range (1, (x+1), 1):
c=0
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
else:
k = k-1
i=i+1
OUTPUT
Enter the number: 15
2
3
5
7
11
13
>>>
9. Matrix Multiplication
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]]
rmatrix = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
rmatrix[i][j] += matrix1[i][k] * matrix2[k][j]
for r in rmatrix:
print(r)
OUPUT
[32, 38, 44, 50]
[68, 83, 98, 113]
[104, 128, 152, 176]
10. Using command Line Arguments
10 a.
import sys
print (len(sys.argv))
OUPUT
10.b
import sys
def word_count(str):
counts = dict()
str1=''.join(str)
words = str1.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count(sys.argv[1:]))
OUPUT
11. Find the most frequent words in a text read from a file
import re
import string
frequency = {}
document_text = open('a.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print (words, frequency[words])
OUTPUT
Have to create a.txt
radha
rama
uma
kala
kiruba
raji
raji rmd
ts=input("Enter string:")
l=[]
l=ts.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
OUPUT
runfile('C:/Users/admin/frc.py', wdir='C:/Users/admin')
Enter string:kala rama uma kala uma
{'kala': 2, 'rama': 1, 'uma': 2}
>>>
What is a pygame?
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer
graphics and sound libraries designed to be used with the Python programming language
if dsqd == 0:
return #division by zero is bad!
pygame.init()
window = pygame.display.set_mode ((600, 400))
main_surface = pygame.Surface ((600, 400))
colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555, 0x666666, 0x777777, 0x888888,
0x999999, 0xaaaaaa, 0xbbbbbb] + [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,
0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000]
#colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888, 0xFFFFFF,
0x808000, 0x008080, 0x800080, 0x800000]
while (True):
# main_surface.fill(0x000000)
pygame.draw.circle (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)
for p in particles:
p.apply_gravity (earth)
p.update ()
pygame.draw.circle (main_surface, p.colour, (int (p.x), int (p.y)), 5, 2)
import sys
import pygame
pygame.init()
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("C:\\Users\\admin\\Desktop//bi.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
ballrect = ballrect.move(speed)
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT