1 Year Lab Python 2017 Manual
1 Year Lab Python 2017 Manual
PROGRAMMING LABORATORY
PAGE STAFF
S.NO DATE PROGRAM MARKS
NO SIGN
Compute the GCD of two
1
numbers.
Find the square root of a number
2
(Newtons method)
Exponentiation (power of a
3
number)
Find the maximum of a list of
4
numbers
5 Linear search and Binary search
7 Merge sort
8 First n prime numbers
9 Multiply matrices
AIM:
ALGORITHM:
1. Start
2. Get the two input number as a, b.
3. If b==0, return the value.
4. Else recursively call the function with the arguments b values and the
remainder when a value is divided by the b value.
5. Return the value which is the GCD of the two numbers.
6. Print the GCD.
7. Stop.
FLOW CHART:
Start
Input
a,b
(()()
if NO
Return
b==0 a
YES
gcd
(b,a%b)
Print GCD
Stop
PROGRAM:
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
OUTPUT:
RESULT:
Thus the program to compute the GCD of two numbers was written and executed
successfully.
EX.NO:02
DATE: FIND THE SQUARE ROOT OF A NUMBER
(NEWTONS METHOD)
AIM:
ALGORITHM:
1. Start
2. Read the input value number.
4. if the condition is false, then square root for n is calculated by
Square root= 0.5**n.
5. Print square root value.
6. Stop
FLOW CHART:
Start
Read n
Stop
PROGRAM:
OUTPUT:
Enter a number: 9
Square Root of 3.00
RESULT:
Thus the program to find the square root of a number (Newtons method) was
written and executed successfully.
EX.NO:03
DATE: EXPONENTIATION (POWER OF A NUMBER)
AIM:
ALGORITHM:
1. Start
2. Read base number and exponent number.
3. if exp==1, then display the result as power of number.
4. if exp>1 then
4.1 for exp no of times multiply base with base.
5. Display the result
6. Stop
FLOW CHART:
Start
Return
(Base) no
If If
no
Exp==1 Exp! =1
yes yes
Base*Power (Base, Exp-
1)
Stop
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: 3
Enter exponential value: 2
Result: 9
RESULT:
AIM:
ALGORITHM:
1. Start
2. Read the i..to n value
3. If verified i>n value
4. Check to max to value i number
5. Check to max to value n number
6. Print max value number
7. Stop
FLOW CHAT:
Start
Input
i..n
YES NO
If value
i>n
Print max
value
Stop
PROGRAM:
def main():
print("Enter a series of numbers separated only by spaces:", end='\t')
n = input().split()
n = [int(i) for i in n]
while len(n) != 1:
if n[0] > n[1]:
n.remove(n[1])
else:
n.remove(n[0])
print("the biggest number is: ", n[0])
main()
OUTPUT:
Enter a series of numbers separated only by spaces: 20 11 8 200 1 4 88
The biggest number is: 200
RESULT:
Thus the program to find the maximum of a list of numbers was written and
executed successfully.
EX.NO:05
DATE: LINEAR SEARCH AND BINARY SEARCH
AIM:
1. Start.
2. Get the list of sorted elements.
3. Get the elements to be found. Let it be x.
4. Start from the first element in the list.
5. One by one compare x with each element of list.
6. If x matches with an element, return the index.
7. If x doesnt match with any of elements, return-1.
8. Stop.
A. LINEAR SEARCH FLOW CHART:
Start
Read num
X=1
if
a[1]=n
Stop
PROGRAM:
A.LINEAR SEARCH
num = [12,44,5,62,2,27,85,5,9]
x = int(input("Enter number to search: "))
found = False
for i in range(len(num)):
if(num[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 number to search: 8
8 is not in list
>>>
Enter number to search: 5
5 found at 2th position
B.BINARY SEARCH ALGORITHM:
1. Start.
2. Get the list of sorted elements.
3. Get the elements to be found. Let it be x.
4. Start from the first element in the list.
5. Mid=L/2.
6. Camper, x with the middle element in the sorted list using mid.
7. If both are matching, than display given element found!!! and terminate.
8. If both are matching, than check whether x is smaller or larger than middle element.
9. If x is smaller than middle element, than repeat from step5 for the left sub list of the
middle element.
10. If x is larger than middle element, than repeat from step5 for the right sub list of the
middle element.
11. If that element also does not match with the search element, then display element
not found in the list!!! and terminate.
12. Stop.
B.BINARY SEARCH FLOW CHART:
Start
First = 1
Last = len -1
no
If
First <=last
yes
Print item not
found
Mid-(first+ last)/2
If
Last=mid-1 A[mid]=n yes
no
Print item
found
If
yes n<a[mid]
no
First =mid-1
Stop
B.BINARY SEARCH PROGRAM:
def bsearch(alist,item):
first=0
last=len(alist)-1
found=False
while first<=last and not found:
midpoint=(first+last)//2
if alist[midpoint]==item:
found=True
print("Element found in position:",midpoint)
else:
if item<alist[midpoint]:
last=midpoint-1
else:
first=midpoint+1
return found
a=[]
n=int(input("Enter upper limits:"))
for i in range(n):
a.append(int(input()))
x=int(input("Enter element to search in the list:"))
bsearch(a,x)
OUTPUT :
RESULT:
Thus the program to search a given element using linear search and binary search
was written and executed successfully.
EX.NO:06
DATE: SELECTION SORT AND INSERTION SORT
AIM:
1. Start.
2. Assume element in alist 0as len.
3. Compare len will all the other elements in the list.
4. If an element lesser than len exit;place it in list 0.
5. Now assume element in list 1 as len; repeat steps 2&3.
6. Repeat until list is sorted.
7. Stop.
A.SELECTION SORT FLOWCHART:
Start
Read alist 0 to
len
Mini position =0
For k in range
(1,i+1)
If nos-list[k]
<nos-list [min
position]
Print after
string
Stop
A. SELECTION SORT PROGRAM:
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,77,31,55,5,20]
selectionSort(alist)
print(alist)
OUTPUT:
1. Start.
2. Read the i value to len.
3. Assume element in alist 0as index.
4. Compare the first and second element arrange in order.
5. Pick third element; compare with elements before, arrange in order.
6. Pick next element; compare with all elements before; arrange in order.
7. Report until till the last element; until the list is sorted.
8. End.
B. INSERTION SORT FLOWCHART:
Start
Read no alist
n=A[i]
Position=1
yes
alist[position]=alist[position-1]
Position=position-1
alist [position
]=temp
Stop
B. INSERTION SORT PROGRAM:
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
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
OUTPUT:
RESULT:
Thus the program to selection sort and insertion sort was written and executed
successfully.
EX.NO:07
DATE: MERGE SORT
AIM:
ALGORITHM:
1. Start.
2. Read the value on a list.
3. If no of items>=1 return else continue.
4. Divide the list into two lists; first list and second list.
5. Sort first list and second list, by dividing each list further into halves.
6. Merge the sorted lists to get sorted list.
7. Stop.
FLOW CHART:
Start
I=0,j=0,k=0
If
len(alist)>1
I=i+1
j=j+1
K=k+1
Stop
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)
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]
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 to Merge Sort was written and executed successfully.
EX.NO:08
DATE: FIRST N PRIME NUMBERS
AIM:
ALGORITHM
1. Start
2. Get the upper limit upto which the prime nos must be displayed.
3. Let it be N.
4. For each number i from 1 till N.
4.1.check if i is prime.
4.2 .if prime display the number.
4.3.else move to next number.
5. Stop.
FLOW CHART:
Start
Read x
for k in range
(1,(x+1),1)
a=i%j
If no
a=0,
c==2
yes
Print i
Stop
PROGRAM:
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:7
2
3
5
7
RESULT:
Thus the program to first N prime numbers was written and executed successfully.
EX.NO:09
DATE: MULTIPLY MATRICES
AIM:
ALGORITHM:
1. Start.
2. Get the number of row and columns for the matrices.
3. Get the elements of all the two matrices, let be A and B.
4. Let R1=and C1=1
5. Let the result matrix be a R*C matrix with values a zero.
6. for each element in row R1 of matrix A.
6.1. for each element in column C1 of matrix B.
6.2. Multiply elements in R1with elements in C1.
6.3sum the product and set the value to result matrixs R1C1 place.
7. Move to next row; R1=R1+1
8. Move to next column; C1=C1+1
9. Display the result matrix.
FLOW CHART:
start
a=[i]ij],b=[i][j],c[i][j[]=0
r[i][j]=a[i][j]*b[k][i]
Print r
Stop
PROGRAM:
OUTPUT:
[38, 44, 50, 56]
[83, 98, 113, 128]
[128, 152, 176, 200]
RESULT:
Thus the program to Multiply Matrices was written and executed successfully.
EX.NO:10
DATE: PROGRAMS THAT TAKE COMMAND LINE
ARGUMENTS (WORD COUNT)
AIM:
To write a python program for takes command line arguments (word count).
.
ALGORITHM:
Start
Input String
Stop
PROGRAM:
OUTPUT:
RESULT:
Thus the program takes command line arguments (word count)
was written and executed successfully.
EX.NO:11
DATE: FIND THE MOST FREQUENT WORDS IN A TEXT
READ FROM A FILE
AIM:
To write a python program for find the most frequent words in a text read from a
file.
ALGORITHM:
Start
word=re.findall(r'\w+',open('test.txt').read().lower())
count=Counter(word).most_common(15)
Stop
PROGRAM:
import re
from collections import Counter
word=re.findall(r'\w+',open('test.txt').read().lower())
count=Counter(word).most_common(15)
print(count)
test.txt
OUTPUT:
RESULT:
Thus the program find the most frequent words in a text read from a file was
written and executed successfully.
EX.NO:12
DATE: SIMULATE ELLIPTICAL ORBITS IN PYGAME
AIM:
ALGORITHM:
3. Define the class for Sun and initialize all the attributes it takes as input .
4. Define the planet class and provide details of all the various planets and their
attributes.
5. End the program with source code.
PROGRAM:
import turtle
import math
class SolarSystem:
def __init__(self, width, height):
self.thesun = None
self.planets = []
self.ssturtle = turtle.Turtle()
self.ssturtle.hideturtle()
self.ssscreen = turtle.Screen()
self.ssscreen.setworldcoordinates(-width/2.0,-height/2.0,width/2.0,height/2.0)
self.ssscreen.tracer(50)
def showPlanets(self):
for aplanet in self.planets:
print(aplanet)
def freeze(self):
self.ssscreen.exitonclick()
def movePlanets(self):
G = .1
dt = .001
for p in self.planets:
p.moveTo(p.getXPos() + dt * p.getXVel(), p.getYPos() + dt * p.getYVel())
rx = self.thesun.getXPos() - p.getXPos()
ry = self.thesun.getYPos() - p.getYPos()
r = math.sqrt(rx**2 + ry**2)
accx = G * self.thesun.getMass()*rx/r**3
accy = G * self.thesun.getMass()*ry/r**3
p.setXVel(p.getXVel() + dt * accx)
p.setYVel(p.getYVel() + dt * accy)
class Sun:
def __init__(self, iname, irad, im, itemp):
self.name = iname
self.radius = irad
self.mass = im
self.temp = itemp
self.x = 0
self.y = 0
self.sturtle = turtle.Turtle()
self.sturtle.shape("circle")
self.sturtle.color("yellow")
def getName(self):
return self.name
def getRadius(self):
return self.radius
def getMass(self):
return self.mass
def getTemperature(self):
return self.temp
def getVolume(self):
v = 4.0/3 * math.pi * self.radius**3
return v
def getSurfaceArea(self):
sa = 4.0 * math.pi * self.radius**2
return sa
def getDensity(self):
d = self.mass / self.getVolume()
return d
def __str__(self):
return self.name
def getXPos(self):
return self.x
def getYPos(self):
return self.y
class Planet:
self.pturtle = turtle.Turtle()
self.pturtle.up()
self.pturtle.color(self.color)
self.pturtle.shape("circle")
self.pturtle.goto(self.x,self.y)
self.pturtle.down()
def getName(self):
return self.name
def getRadius(self):
return self.radius
def getMass(self):
return self.mass
def getDistance(self):
return self.distance
def getVolume(self):
v = 4.0/3 * math.pi * self.radius**3
return v
def getSurfaceArea(self):
sa = 4.0 * math.pi * self.radius**2
return sa
def getDensity(self):
d = self.mass / self.getVolume()
return d
def show(self):
print(self.name)
def __str__(self):
return self.name
def getXPos(self):
return self.x
def getYPos(self):
return self.y
def getXVel(self):
return self.velx
def getYVel(self):
return self.vely
def createSSandAnimate():
ss = SolarSystem(2,2)
numTimePeriods = 20000
for amove in range(numTimePeriods):
ss.movePlanets()
ss.freeze()
createSSandAnimate()
OUTPUT:
RESULT:
Thus the program takes Simulate Elliptical Orbits In Pygame was written and
executed successfully.
EX.NO:13
DATE: SIMULATE BOUNCING BALL USING PYGAME
AIM:
ALGORITHM:
ballpic = image.load('ball.png')
done = False
RESULT:
Thus the program takes Simulate Bouncing Ball Using Pygame was
written and executed successfully.
VIVAVOCE QUESTIONS: