Python Lab Manual
Python Lab Manual
Python Lab Manual
PROGRAMMING LABORATORY
GE8161
R2017
(CBCS)
LAB MANUAL
G.K.M
COLLEGE OF ENGINEERING & TECHNOLOGY
CHENNAI-63
GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY L T P C
0042
OBJECTIVES:
• To write, test, and debug simple Python programs.
• To implement Python programs with conditionals and loops.
• Use functions for structuring Python programs.
• Represent compound data using Python lists, tuples, and dictionaries.
• Read and write data from/to files in Python.
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
Python 3 interpreter for Windows/Linux
TOTAL: 60 PERIODS
OUTCOMES:
Upon completion of the course, students will be able to
• Write, test, and debug simple Python programs.
• Implement Python programs with conditionals and loops.
• Develop Python programs step-wise by defining functions and calling them.
• Use Python lists, tuples, dictionaries for representing compound data.
• Read and write data from/to files in Python.
ii
LIST OF EXPERIMENTS
5 Linear search 12
6 Binary search 15
7 Selection sort 22
8 Insertion sort 25
9 Merge sort 29
11 Multiply matrices 36
iii
iv
How to Open Python Interpreter.
Opening Python in Scripting mode
1. Click “Start All Programs Python 3.6 IDLE(Python 3.6 32-bit)”
2
1. Compute the GCD of two numbers.
Aim:
To write a Python program to compute the Greatest Common Divisor of
given two numbers.
Algorithm:
1. Start.
2. Read two variables ‘a’ and ‘b’.
3. Calculate remainder using a%b.
4. repeat step4 until remainder!=0
4.1.Assign value of ‘b’ to ‘a’.
4.2.Assign value of ‘remainder’ to ‘b’.
4.3.Compute ‘remainder’ using a%b.
5. Print the value of ‘b’ as GCD.
6. Stop.
Flowchart:
3
Program:
a=int(input("Enter first number"))
b=int(input("Enter second number"))
rem =a%b
while rem!=0:
a=b
b=rem
rem=a%b
print("Greatest Common Divisior for given number is",b)
Output:
Result:
Thus the program for computing GCD is executed and result is verified.
4
2. Find the square root of a number (Newton‘s method)
Aim:
To write the Python program to find the square root of given number using
Newton’s method.
Algorithm:
1. Start.
2. Read the value of a.
3. Initialize approximate value square_root as a/2.
4. Repeat step 4.1 for 10 times.
4.1.Calculate square_root as(0.5*(square_root +(a/square_root)))
5. Print square_root value.
6. Stop.
Flowchart
5
Program
a = float(input('What number would you like to squareroot?'))
sqr_root = a/2
for i in range(0,10):
sqr_root = (0.5*(sqr_root+(a/sqr_root)))
print (sqr_root)
Output:
Result:
Thus the program for computing square root value is executed and output
is verified.
6
3. Exponentiation (power of a number)
Aim:
To write a Python program to find the exponentiation of given numbers.
Algorithm:
1. Start.
2. Read the base value.
3. Read the exponent.
4. Compute power as power=base**exponent.
5. Print the value of power.
6. Stop.
Flowchart:
Program:
7
base = int(input(“Enter base value”))
exponent = int(input(“Enter exponent value”))
power=base**exponent
print(“Exponentiation of given number is”,power)
Output:
Result:
Thus the program to find exponentiation is executed and output is
verified.
8
4. Find the maximum of the given list of numbers.
Aim:
To write a Python program to find maximum of numbers from the given
list.
Algorithm:
1. Start.
2. Read the number of items as‘n’.
3. Use for loop to input n numbers.
3.1. Append the entered values to a list.
4. Assign first value of list as max value.
5. Repeat step 5.1 and 5.2 till all the values in the list are exhausted
5.1. If list element > max value
5.1.1. Assign list element to max value.
5.2. Increment the element number
6. Print maximum valueas the content of max value.
7. Stop.
Flowchart
9
10
Program:
a=list()
n=int(input("Enter total no of items"))
for i in range(n):
a.append(int(input("Enter value"+str(i+1)+" ")))
maxi=a[0]
for i in range (0,n):
if a[i]>maxi:
maxi=a[i]
print("Given list=",a)
print("Max value" ,maxi)
Output:
Result:
Thus the program to find the maximum value of given list is executed and
output is verified.
11
5. Linear Search
Aim:
To perform linear search in Python Programming.
Algorithm:
1. Start.
2. Input a list of n numbers.
3. Initialize flag=-1
4. Input the element to be searched as search element.
5. Repeat step 4.1 and 4.2 till all the values in the list are exhausted.
5.1. Iflist[element] and search element are equal
5.1.1. Set flag=1.
6. If flag =1
6.1.Print “element found”.
7. Else
7.1.Print “element not found”
8. Stop.
12
Flowchart:
13
Program:
a=list()
n=int(input("Enter total no of items"))
for i in range(n):
a.append(int(input("Enter value"+str(i+1)+" ")))
search_key=int(input("Enter the value to search"))
position = - 1
print("Given list=",a)
for i in range(n):
if a[i]==search_key:
position=i+1
print(search_key," is found in position",position)
if(position<0):
print(search_key," is not found")
Output
Result:
Thus the program to perform linear search is executed and output is verified.
14
6. BINARY SEARCH
Aim:
To perform binary search in Python Programming
Algorithm:
1. Start.
2. Input a sorted list of‘n’ numbers.
3. Input the element to be searched.
4. Assign initial values of ‘initial’ as 0 and ‘final’ as n-1.
5. Compute the location of middle element using (initial + final)/2.
6. Repeat steps 6.1 and 6.2till initial<= final
6.1.If middle element=search element
6.1.1. print element found
6.2.else
6.2.1. if search element<middle element
6.2.1.1. set final = middleelement-1 and repeat steps 5 and 6
6.2.2. else search element>middle element
6.2.2.1. set initial=middle element+1 and repeat steps 5 and 6
7. If initial>final
7.1.Print search element not found.
8. Stop.
15
Flowchart:
16
Program:
a=list()
n=int(input("Enter total no of items"))
for i in range(n):
a.append(int(input("Enter value"+str(i+1)+" ")))
search=int(input("Enter element to search"))
initial=0
final=n-1
print("Given list=",a)
while initial<=final :
middle=(initial+final)//2
if search==a[middle]:
print(search,"is found in position", middle+1)
break
else:
if search<a[middle]:
final=middle-1
else:
initial=middle+1
if initial>final:
print(search,"is not found")
17
Output:
Result:
Thus the program to perform binary search is executed and output is
verified.
18
7. Selection Sort
Aim:
To write a Python program to perform selection sort.
Algorithm:
1. Start
2. Input a list of n numbers.
3. Repeat step 3 until i < n
3.1. Assign j = j + 1
3.2.Repeat step 3.2 until j < n
3.2.1. Check if list [i] > list [ j ]
3.2.1.1. Then swap using temporary variable temp=a[i]
3.2.1.2. Reassign a[ i ] = a[ j ]
3.2.1.3. Reassign a[ j ] = temp
4. Print the sorted list
5. Stop
19
Flowchart
20
Program
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("List before sorting",a)
for i in range(0,n):
j=i+1
for j in range(j, n):
if a[i]> a[j]:
temp=a[i]
a[i]=a[j]
a[j]=temp
print("Sorted list(using Selection Sort)=",a)
Output:
Result:
Thus the Python program to perform selection sort is executed and output
is verified.
21
8. Insertion Sort
Aim:
To write a Python program to perform insertion sort for the given list.
Algorithm:
1. Start
2. Input a list of n numbers
3. Initialize i = 1
4. Repeat step 4 until i < n
4.1. Assign key = list[i] and j = i – 1
4.2.Repeat step 4.2 until j > = 0 and key <list [j]
4.2.1. Assign list [ j + 1 ] = list [ j ]
4.2.2. Reassign j=j – 1
4.3. Assign list [ j + 1 ] = key
5. Print the sorted list
6. Stop
22
Flowchart:
23
Program:
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Before sorting",a)
for i in range(1,n):
key=a[i]
j=i–1
while j>=0 and key<a[j]:
a[j+1]=a[j]
j – =1
a[j+1]=key
print("After sorting(using insertion sort)",a)
Output:
Result:
Thus the program to perform insertion sort is executed and output is
verified.
24
9. MERGE SORT
Aim:
To perform merge sort in Python Programming
Algorithm:
9. Start.
10.Read a list of‘n’ numbers.
11.Call mergesort() function
11.1. Check if length of list is <2
11.1.1. Return list
11.2. Find middle using length of list divided by 2
11.3. Call mergesort() function for left list [:middle]
11.4. Call mergesort() function for right list [middle:]
11.5. Call merge() function
12.merge(left,right) function
12.1. Initialize result=[] as empty list
12.2. Initialize i=0, j=0
12.3. Repeat step 4.3 until i<len(left) and j<len(right)
12.3.1. If left[i]<=right[j]
12.3.1.1. Append left[] list of values to result[]
12.3.1.2. Increment i by 1
12.3.2. Else
12.3.2.1. Append right[] list of values to result[]
12.3.2.2. Increment j by 1
12.4. result =result+left[i:]
12.5. result =result+right[j:]
12.6. Return result
13.Print result
14.Stop.
25
Flowchart:
26
Program:
def merge(left, right):
result = []
i, j = 0, 0
while (i < len(left) and j<len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
result=result+left[i:]
result=result+right[j:]
return result
def mergesort(list):
if len(list) < 2:
return list
middle = len(list)//2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Unsorted list is",a)
print("Sorted list is")
print(mergesort(a))
27
Output:
Result:
Thus the program to perform merge sort is executed and output is
verified.
28
10. Find n prime numbers
Aim:
To write a Python program to find n prime numbers.
Algorithm:
6. Start
7. Read n as number of prime number to be printed
8. Create an empty list
9. Initialize a value begin = 2
10.Repeat step 5 until len(list) !=n
10.1. Repeat step 5.1 until 2 to begin//2+1
10.1.1. If begin%i = =0
10.1.1.1. break
10.2. Append value of begin to list
10.3. Increment begin=begin+1
11.Print the list
12.Stop
29
Flowchart
30
Program
n=int(input("Enter the number of Prime numbers to print"))
prime=[]
begin=2
while len(prime)!=n:
for i in range(2,begin//2+1):
if begin%i==0:
break
else:
prime.append(begin)
begin+=1
print("List of first",n,"prime numbers are",prime)
Output:
Result:
Thus the Python program to find first n prime numbers is executed and
output is verified.
31
11.Matrix Multiplication
Aim:
To write a Python program to perform multiplication of two matrices.
Algorithm:
7. Start
8. Initialize three list x, y and result
9. Read the column and row size
10.Repeat step 4 for getting matrix x
10.1. Repeat step 4.1 until i<= columnsize
10.1.1. Initialize a temporary list
10.1.1.1. Repeat step 4.1.1.1 until j <= rowsize
10.1.1.1.1. Append the read value to temporary list
10.1.2. Append the temporary list to x matrix
11.Repeat step 5 for getting matrix y
11.1. Repeat step 5.1 until i<=column size
11.1.1. Initialize a temporary list
11.1.1.1. Repeat step 5.1.1.1 until j <= row size
11.1.1.1.1. Append the read value to temporary list
11.1.2. Append the temporary list to y matrix
12.Repeat step 6 for result matrix
12.1. Repeat step 6.1 until i<=column size
12.1.1. Initialize a temporary list
12.1.1.1. Repeat step 6.1.1.1 until j <=rowsize
12.1.1.1.1. Append zero to temporary list
12.1.2. Append the temporary list to result matrix
13.Repeat step 7 until i<= length of x matrix
13.1. Repeat step 7.1 until j<= length of y matrix
13.1.1. Repeat step 7.1.1 until i<= length of y matrix
13.1.1.1. Calculate result [ i ][ j ] += x[i][k] * y[k][j]
14.Print result matrix
15.Stop
32
Flowchart:
33
Program:
x=list()
y=list()
result=list()
m=int(input("Enter row size"))
n=int(input("Enter column size"))
for i in range(m):
temp=[]
for j in range(n):
temp.append(int(input("Enter first matrix")))
x.append(temp)
print("\nFirst matrix=",x)
for i in range(m):
temp=[]
for j in range(n):
temp.append(int(input("Enter second matrix")))
y.append(temp)
print("\nSecond Matrix=",y)
for i in range(m):
temp=[]
for j in range(n):
temp.append(int(0))
result.append(temp)
for i in range(len(x)):
for j in range(len(y)):
for k in range(len(y)):
result[i][j] = result[i][j] + x[i][k] * y[k][j]
print("\nMultiplication of two matrix =")
for r in result:
print(r)
34
Output:
Result:
Thus the program to perform multiplication of two matrices is executed
and output is verified.
35
12. Command line argument (Word count)
Aim:
To write a Python program to accept command line argument and to
count the words.
Algorithm:
1. Start
2. Read the file name
3. Open the file
4. Repeat step 4 until all lines are counted
4.1.Repeat step 4.1 until all words are counted
4.1.1. Count=count+1
5. Print count
6. Stop
Flowchart:
36
Program:
def open_file(filename):
count=0
fp=open(filename)
for line in fp:
for word in line.split():
count=count+1
print(count)
open_file(input("Enter file name with extension"))
Output:
Result:
Thus the program to accept command line argument and to count words
is executed and output is verified.
37
13.Most frequent word in file
Aim:
To write a Python program to find most frequent words in the file.
Algorithm:
1. Start
2. Read the file name
3. Initialize a list and a dictionary
4. Open file
5. Repeat step 5 for all the lines
5.1. Repeat step 5.1 for each word
5.1.1. Append the each word to the dictionary as key increment value by
1 for each reoccurrence of key
6. Repeat step 6 for each key in dictionary
6.1.Append the key and value to the list
7. Print the list
8. Stop
38
Flowchart:
39
Program:
def open_file(filename):
count=[];
freq_word={}
fp=open(filename)
for line in fp:
for word in line.split():
word=word.lower()
freq_word[word] = freq_word.get(word,0)+1
for key,value in freq_word.items():
count.append((value,key))
count.sort()
count.reverse()
return count
t=open_file(input("Enter file name with extension"))
for freq, word in t[0:10]:
print(word, '\t', freq)
40
Output:
Result:
Thus the Python program to find the most frequent word is executed and
output is verified.
41
14. Simulate elliptical orbits usingPygame
Aim:
To simulate the elliptical orbits usingPygame
Algorithm:
1. Install required packages
2. Import required packages
3. Set screen size
4. Define required parameters to simulate elliptical orbit
5. Display created objects in Pygame surface
6. Stop
Program
importpygame, math
frompygame.locals import *
from random import randint
screen = pygame.display.set_mode([500,500])
clock = pygame.time.Clock()
pygame.init()
class ellipse():
def __init__(self, vel = [1, 1], mass = 100000, pos = [100, 100], length =
100000):
self.v = vel
self.m = mass
self.size = mass/1000000
self.pos = pos
self.len = length
self.path = [[pos[0], pos[1]]]
def update(self):
self.pos[0] += self.v[0]
self.pos[1] += self.v[1]
42
self.path.append([self.pos[0], self.pos[1]])
iflen(self.path) == self.len:
self.path.pop(0)
class orbits():
def __init__(self, planetList, iterations, mass = 10000000, gconst = (6 * 10 ** -
9)):
self.plnt = planetList
self.iter = iterations
self.mass = mass
self.size = int(mass/1000000)
self.gC = gconst
def draw(self):
pygame.draw.circle(screen, [0, 0, 0], [250, 250], self.size)
for p in self.plnt:
pygame.draw.rect(screen, [0, 0, 0], [p.pos[0], p.pos[1], p.size, p.size])
pygame.draw.lines(screen, [0, 0, 0], False, p.path)
def update(self):
fori in range(self.iter):
for p in self.plnt:
d = math.sqrt((p.pos[0] - 250) ** 2 + (p.pos[1] - 250) ** 2)
f = (self.gC * self.mass * p.m)/(d ** 2)
vect = [((250 - p.pos[0]) / d) * f, ((250 - p.pos[1]) / d) * f]
p.v[0] += vect[0]
p.v[1] += vect[1]
p.update()
self.draw()
a = ellipse([4,0])
b = ellipse([4, 0])
43
o = orbits([b], 100)
while True:
screen.fill([255, 255, 255])
o.update()
for event in pygame.event.get(True):
ifevent.type == QUIT:
pygame.quit()
pygame.display.update()
clock.tick(20)
Output:
Result:
Thus the program to simulate the elliptical orbits usingPygame is
executed successfully and output is verified.
44
15.Simulate bouncing ball using Pygame
Aim:
To write a Python program to simulate bouncing ball using Pygame
Algorithm:
1. Import required packages
2. Set screen size
3. Define required parameters to simulate bouncing ball
4. Display created objects in Pygame surface
5. Stop
Program
import sys, pygame
pygame.init()
size = width, height = 700, 300
speed = [2, 2]
background = 255, 255, 255
screen= pygame.display.set_mode(size)
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
if ballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
45
Output:
Result:
Thus the program to simulate the bouncing ball usingPygame is executed
successfully and output is verified.
46