Ge8161 Python Programming Lab Record
Ge8161 Python Programming Lab Record
Date:
Aim:
To compute the GCD of two numbers
Algorithm:
1. Read two input values using input function
2. Convert them into integers
3. Define a function to compute GCD
a. Find smallest among two inputs
b. Set the smallest
c. Divide both inputs by the numbers from 1 to smallest+1
If the remainders of both divisions are zero
Assign that number to gcd
d. Return the gcd
4. Call the function with two inputs
5. Display the result
Flow Chart:
Start
Print Result
Stop
1
A
ComputeGCD(x,y)
True False
If x>y
Smaller=y Smaller=x
False
For
i<=smaller+1
True
False
If x & y is
divisible by
i
True
Set GCD=i
Program :
def computeGCD (x, y) :
Return
if x < y :
smaller = x
else:
smaller = y
for i in range(1, smaller+1) :
if (x % i == 0) and (y % i == 0) :
gcd = i
return gcd
2
Ex. No 2 FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S METHOD)
Date:
Aim:
To find the square root of a number (Newton’s method)
Algorithm:
1. Read one input value using input function
2. Convert it into float
3. Find the square root of the given number using the formula inputvalue ** 0.5
4. Print the result
5. Exit.
Flow Chart:
Start
X=float(A)
C=X**0.5
Stop
3
Program :
A=input("enter a value")
x=float(A)
C=x**0.5
print("square root of ", x , "is =",C)
Output:
C:\Python36-32\mypgm>ex2.py
Enter a value: 16
Square root of 16 is= 4.0
Result:
Thus, the program to To find the square root of a number (Newton’s method) has been executed
successfully.
4
Ex. No 3 EXPONENTIATION (POWER OF A NUMBER)
Date:
Aim:
To write a python program to find exponentiation (power of a Number)
Algorithm:
1. Create a function using def
2. Check if exponent value
a. If exponent == 1
Return base value
b. else
Recursively call the function with (base, exponent-1)
Multiply the result returned by each recursive call with base value and Return the
final result
3. Read base & exponent values using input function
4. Call the function & Print the Result
Flowchart:
Start
Print Result
Stop
5
A
power(base,exp)
True False
If
exp==1
Program:
def power(base,exp):
if exp==1:
return(base)
if exp!=1:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Output:
Enter base: 2
Enter exponential value: 2
Result: 4
Result:
Thus, the program to find exponentiation (power of a Number) is executed successfully
6
Ex. No 4a FIND THE MAXIMUM OF A LIST OF NUMBERS
Date:
Aim:
To write a python program to find Maximum of a List of Numbers
Algorithm:
1. Initialize a List
2. Read the Number of Elements
3. Read the List values one by one
4. Set Max = first element of the list
5. Compare Max with List elements
6. If Max< List element
7. Set Max= List element
8. Continue the step 5 until reach the end of the List
9. Print the Max
7
Flowchart:
START
IF
LIST[I] >
MAX
MAX=LIST[I]
PRINT THE
MAX
STOP
8
Program :
def MaxList():
list1=[]
N=int(input("Enter Number of Values"))
for i in range (0,N):
x=int(input("Enter a Value"))
list1.append(x)
print(list1)
Max=list1[0]
j=1
while j<N:
if list1[j]>Max :
Max=list1[j]
j=j+1
print(" The Maximum Element in the List is ",Max)
MaxList()
Output:
Enter Number of Values: 3
Enter a Value56
Enter a Value76
Enter a Value43
[56, 76, 43]
The Maximum Element in the List is 76
Result:
Thus, the program to find Maximum of a List of Numbers is executed successfully
9
Ex. No 4b REMOVING ALL THE DUPLICATE ELEMENTS IN A LIST
Date:
Aim:
To write a python program to remove all duplicate elements in the list
Algorithm:
1. Cretae a list using creatlist()
a. Enter number of elements
b. Append the values one by one in the list
2. Print the list
3. Pass the list as input to removeduplicat() function
a. Initialize an empty list
b. Initialize an empty set ( set only contains the unique elements used to remove the duplicates)
c. For every element in the list,
i. if the element is not in the set
1. Add that element into both the list & set
ii. Else repeat the step 3b until reach the end of the list
d. Return this new list ,
4. Print the list after removing the duplicates
Flowchart:
Start
A
10
B
Removeduplicate(List)
False
For Every Element in
the List
True
11
Program :
def createlist():
list1=[]
N=int(input("Enter Number of Values"))
for i in range (0,N):
x=int(input("Enter a Value"))
list1.append(x)
return list1
def removeduplicate(A):
output=set()
list2=[]
for i in A:
if i not in output:
output.add(i)
list2.append(i)
return list2
A=createlist()
print(A)
result=removeduplicate(A)
print(result)
Output :
Enter Number of Values4
Enter a Value11
Enter a Value22
Enter a Value11
Enter a Value22
[11, 22, 11, 22 ]
[11, 22 ]
Result:
Thus, the program to remove all duplicate elements in the list is executed successfully
12
Ex. No 5a LINEAR SEARCH
Date:
Aim :
To write a python program to perform Linear Search
Algorithm:
1. Define a function called LS()
2. Define a empty list Set a flag to 0
3. Read number of elements, store it in a variable called N
4. Read the values one by one using for loop
a. Append each value into the List
5. Print the list
6. Read key values to be searched in the list
7. Check whether key present in the list one by one using loop statement
a. if found ,Set flag to 1
8. If flag==1 , then print “key is found at position pos_value“
9. Else , print “key not found”
10. Call the function LS() at end of code
13
Flowchart:
START
FOR I IN RANGE(O,N)
READ ELEMENT
ONE BY ONE
FOR I IN RANGE(O,N)
IF
LIST[I]==KEY
STOP
14
Program:
def LS() :
list1=[]
flag=0
N=int(input("enter no. of elements"))
print("Enter values one by one")
for i in range(0,N):
a=int(input("enter a value"))
list1.append(a)
print(list1)
key=int(input("enter the Key value"))
for i in range(0,N) :
if key == list1[i]:
flag=1
break
if flag==1:
print(key ," is found in the list1 at position ",i+1 )
else:
print(key ," is not found in the list1")
LS()
Output:
enter no.of values4
Enter values one by one
enter value11
enter value22
enter value33
enter value44
[11, 22, 33, 44]
enter key value22
22 is present in the List at position 2
Result:
Thus, the Linear Search has been performed successfully
15
Ex. No 5b BINARY SEARCH
Date:
Aim:
To write a python program to perform Binary search
Algorithm:
1. Define a function called BS(alist,key)
2. Set a first & last values to point the boundary of list to be searched
3. Find mid position of the given list called alist
4. Compare key with mid position element
a. If mid element == key
Set found=True, print key founf
b. If mid element < key
Set last= midposition -1
c. If mid element > key
Set first= midposition +1
5. Continue the steps 3 & 4 until the element found or reach the end of the list
6. Initialize a list ( elements in sorted order)
7. Call BS() with name of list & key value : BS(alist,key)
8. Print the result
16
Flowchart:
START
First = 0
Last = len(alist)-1
Found = 0
While
First<=Last
Midpoint = (First+Last)//2
if key ==
alist[midpoint
]
Found = True
IF
key<alist[mid
point]
Y N
Last=midpoint-1 First=midpoint+1
17
Program :
Output:
13 is found in the list [0, 1, 2, 8, 13, 17, 19, 32, 42] at position 5
100 is not found in the list
Result:
Thus, the Binary Search has been performed successfully
18
Ex. No 6a SELECTION SORT
Date:
Aim:
To write a python program to perform selection sort
Algorithm:
1. Define a function selection()
2. Call this function by passing a list as input to this function
3. For every element in the list
a. Pick the first element
b. Compare it with the remaining elements of the list
c. Find an element that is smaller than the first one
d. Swap these two elements (smallest,first)
e. Now, the smallest element placed at first position, Do the step 3 for next element
f. Continue the step3 until all the elements are arranged in sorted order
4. Return the sorted list
5. Display the sorted list
19
Flowchart:
Start
for i in range(len(list2))
If any
element is
smaller
Stop
20
Program:
def selection(list2):
for i in range(len(list2)):
least=i
for k in range(i+1,len(list2)):
if list2[k] < list2[least]:
least=k
list2=swap (list2,least,i)
return list2
def swap(A,x,y):
tmp=A[x]
A[x]=A[y]
A[y]=tmp
return A
list1=[25,9,8,3,5,7,10]
print("Before Sorting " ,list1)
result=selection(list1)
print("After Sorting " ,result)
Output:
Before Sorting [25, 9, 8, 3, 5, 7, 10]
After Sorting [3, 5, 7, 8, 9, 10, 25]
Result:
Thus, the program for selection sort has been executed successfully
21
Ex. No 6b INSERTION SORT
Date:
Aim:
To write a python program to perform Insertion sort
Algorithm:
1. Define a function Insertion()
a. For every element in the list
i. Set current element
ii. Compare the current element with its previous adjacent element
If current element < previous adjacent element
Swap these two elements
Continue the step (ii) until all the predecessors to the current element
are arranged in order
iii. Repeat the step 1a until all elements in the list are arranged in sorted order
b. Print the sorted list
2. Get a List
3. Call the function by passing the list as input
4. Display the result
22
Flowchart:
Start
N
If current
element is
greater
Stop
23
Program:
def insertion(a):
for i in a :
j = a.index(i)
while j>0 :
if a[j-1] > a[j] :
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print(“After Sorting : ”,a)
list1 = [16,19,11,15,10,12,14,5]
print(“Before Sorting :”,list1)
insertion(list1)
Output:
Before Sorting: [16, 19, 11, 15, 10, 12, 14, 5]
After Sorting: [5, 10, 11, 12, 14, 15, 16, 19]
Result:
Thus, the program for Insertion sort has been executed successfully
24
Ex. No 7 MERGE SORT
Date:
Aim:
To write a python program to perform Merge sort
Algorithm:
25
Flowchart:
Start
If False
len(list) > 1
True
Stop
26
Program:
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
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
27
Output:
('Splitting ', [54, 26, 93, 17, 77, 31, 44, 55, 20])
('Splitting ', [54, 26, 93, 17])
('Splitting ', [54, 26])
('Splitting ', [54])
('Merging ', [54])
('Splitting ', [26])
('Merging ', [26])
('Merging ', [26, 54])
('Splitting ', [93, 17])
('Splitting ', [93])
('Merging ', [93])
('Splitting ', [17])
('Merging ', [17])
('Merging ', [17, 93])
('Merging ', [17, 26, 54, 93])
('Splitting ', [77, 31, 44, 55, 20])
('Splitting ', [77, 31])
('Splitting ', [77])
('Merging ', [77])
('Splitting ', [31])
('Merging ', [31])
('Merging ', [31, 77])
('Splitting ', [44, 55, 20])
('Splitting ', [44])
('Merging ', [44])
('Splitting ', [55, 20])
('Splitting ', [55])
('Merging ', [55])
('Splitting ', [20])
('Merging ', [20])
('Merging ', [20, 55])
28
('Merging ', [20, 44, 55])
('Merging ', [20, 31, 44, 55, 77])
('Merging ', [17, 20, 26, 31, 44, 54, 55, 77, 93])
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Result:
Thus, the program for merge sort has been executed successfully
29
Ex. No 8 FIRST N PRIME NUMBERS
Date:
Aim:
To write a python program to find first N prime Numbers
Algorithm:
1. Read lower & Upper bound values for the Range
2. Foe each number in the Range
3. Divide the num by 2 to num-1
4. Check the remainder
If Remainder == 0 then,
Num is not a prime number.
Else
Print the Number as Prime
5. Repeat the Steps 2 to 4 until reach the Upper bound of the Range
30
Flowchart:
START
IF NUM > 1
Yes
IF NUM %
I ==0
No
PRINT NUM
STOP
31
Program :
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num%i) == 0:
break
else:
print(num)
Output:
Enter lower range: 2
Enter upper range: 10
Prime numbers between 1 and 10 are:
2
3
5
7
Result:
Thus, the program to find first N prime Numbers has been executed successfully
32
Ex. No 9 MULTIPLICATION OF TWO MATRICES
Date:
Aim:
To write a python program to multiply two matrices
Algorithm:
1. Create two lists with nested index
2. Initialize an empty list
3. Multiply two matrices
4. Store the results into empty list
5. Display the result
33
Flowchart:
START
C[I][J] = 0
PRINT C MATRIX
STOP
34
Program:
for r in rmatrix:
print(r)
Output:
[6, 6, 6, 6]
[6, 6, 6, 6]
[6, 6, 6, 6]
Result:
35
Thus, the program to multiply two matrices has been executed successfully
Ex. No 10 FIND THE MOST FREQUENT WORDS IN A TEXT READ FROM A FILE
Date:
Aim:
Write a python program to find the most frequent words in a text read from a file
Algorithm:
1. Get the input file to be read.
2. Initialize num_words to zero.
3. Open the input file in read mode.
4. Use for loop to check the blank space, if there is a space then split the words and counts the words.
5. Repeat the step 4 until reach end of file.
6. Print the number of words.
Flowchart:
Start
Initialize num_words=0
Is blank
space?
Stop
36
Program:
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Output:
Enter file name: data1.txt
Number of words:
4
Result:
Thus, the program to find the most frequent words in a text read from a file has been executed
successfully
37
Ex. No 11 WORD COUNT USING COMMAND LINE ARGUMENTS
Date:
Aim:
To write a python program to implement word count using command line arguments
Algorithm:
38
Flowchart:
Start
If False
len(list)>
2
Error
Data=read the contents
Call count_words()
Call count_lines()
Stop
39
Program:
#e11.py
import sys
if len(sys.argv) < 2:
print("Usage: python word_count.py <file>")
exit(1)
def count_words(data):
words = data.split(" ")
num_words = len(words)
return num_words
def count_lines(data):
lines = data.split("\n")
for l in lines:
if not l:
lines.remove(l)
return len(lines)
filename = sys.argv[1]
f = open(filename, "r")
data = f.read()
f.close()
num_words = count_words(data)
num_lines = count_lines(data)
print("The number of words: ", num_words+num_lines-1)
print("The number of lines: ", num_lines)
Output:
C:\python27> e11.py data1.txt
Enter file name: data1.txt
The number of words: 7
The number of lines: 2
Result:
Thus, the program to implement word count using command line arguments has been
executed successfully.
40
Ex. No 12 SIMULATE ELLIPTICAL ORBITS IN PYGAME
Date:
Aim:
Write a python program to simulate elliptical orbits in pygame
Algorithm:
Program:
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.circle(screen, (255,255,255), [150, 95], 5, 3)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [135, 95], 5, 3)
pygame.draw.circle(screen, (255,255,255), [120, 95], 5, 3)
pygame.draw.circle(screen, (255,255,255), [105, 100], 5, 3)
pygame.draw.circle(screen, (255,255,255), [90, 110], 5, 3)
41
pygame.draw.circle(screen, (255,255,255), [85, 130], 5, 3)
pygame.draw.circle(screen, (255,255,255), [85, 150], 5, 3)
pygame.draw.circle(screen, (255,255,255), [90, 170], 5, 3)
pygame.draw.circle(screen, (255,255,255), [110, 185], 5, 3)
pygame.draw.circle(screen, (255,255,255), [140, 195], 5, 3)
pygame.draw.circle(screen, (255,255,255), [170, 195], 5, 3)
pygame.draw.circle(screen, (255,255,255), [200, 190], 5, 3)
pygame.draw.circle(screen, (255,255,255), [230, 180], 5, 3)
pygame.draw.circle(screen, (255,255,255), [250, 160], 5, 3)
pygame.draw.ellipse(screen, (255,0,0), [100, 100, 100, 70], 10)
pygame.display.flip()
Output:
Result:
Thus, the program to simulate elliptical orbits in pygame has been executed successfully.
42
Ex. No 13 SIMULATE BOUNCING BALL USING PYGAME
Date:
Aim:
Write a python program to simulate bouncing ball using pygame
Algorithm:
Program:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
43
pygame.draw.circle(screen, (0,0,0), [200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [250, 150], 10, 0)
pygame.display.update()
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Output:
Result:
Thus, the program to simulate elliptical orbits in pygame has been executed successfully.
44