Python Lab
Python Lab
Aim:
To write a Python program to find GCD of two numbers.
Algorithm:
1. Define a function named computeGCD()
2. Find the smallest among the two inputs x and y
3. Perform the following step till smaller+1
Check if ((x % i == 0) and (y % i == 0)), then assign GCD=i
4. Print the value of gcd
Program:
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
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The GCD. of", num1,"and", num2,"is", computeGCD(num1, num2))
Sample Input/Output
Enter first number: 25
Enter second number: 30
The GCD. of 25 and 30 is 5
Result:
Thus the Python program to compute GCD of two numbers is executed successfully
and the output is verified.
1
FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S METHOD)
Aim:
To write a Python Program to find the square root of a number by Newton’s Method.
Algorithm:
1. Define a function named newtonSqrt().
2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approx to perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx
Program:
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
return approx
Result:
Thus the Python program for finding the square root of a given number by
Newton’s Method is executed successfully and the output is verified.
2
EXPONENTIATION (POWER OF A NUMBER)
Aim:
Algorithm:
Program:
def power(base,exp):
if exp>1:
return (base*power(base,exp-1))
else:
return(base)
base=int(input("Enter base value: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Sample Input/Output
Enter base: 25
Enter exponential value: 3
Result: 15625
Result:
3
FINDING THE MAXIMUM OF A LIST OF NUMBERS
Aim:
Algorithm:
Program:
l=[]
n=int(input("enter the upper limit: "))
for i in range(0,n):
num=int(input("enter the numbers: "))
l.append(num)
maxno=l[0]
for i in range(1,n):
if l[i]>maxno:
maxno=l[i]
print("The maximum number is: ",maxno)
4
Sample Input/Output
enter the upper limit: 4
enter the numbers: 76575
enter the numbers: 766756
enter the numbers: 7576
enter the numbers: 9897
The maximum number is: 766756
Result:
Thus a Python Program to find the maximum from the given list of numbers is
successfully executed and the output is verified.
5
LINEAR SEARCH
Aim:
To write a Python Program to perform Linear Search Algorithm:
Algorithm:
Program:
def linearsearch(a):
x=0
# Searching element in a list (Linear Search)
for i in range(0,n):
if a[i]==key:
print ("Search element", key," is found at possition:",i+1 )
x=x+1
if x==0:
print("Search element",key,"is not found")
a=[]
# reading input values
n=int(input("Enter no. of elements:"))
for i in range(0,n):
num=input("enter the list element:")
a.append(num)
6
key=input("Enter the key element to be searched:")
linearsearch(a)
Sample Input/Output:
Result:
Thus the Python Program to perform linear search is executed successfully and the output
is verified.
7
BINARY SEARCH
Aim:
To write a Python program to search an element in a list of elements using Binary
search technique.
Algorithm:
1. Start
2. Get list of elements from the user
3: Get the number to be searched
4. Found<-False
5. While not found and first <=top
if List[Midpoint]=ItemSought Then
ItemFound=True
Elif first>=Last Then
SearchFailed=True
Elif List[Midpoint]>ItemSought Then
Last=Midpoint-1
Else
First=Midpoint+1
End if
End While
6. Stop
8
Program:
def binary_search(a,n,key):
low=0
high=n
while(low<=high):
mid=int((low+high)/2)
if(key==a[mid]):
return mid
elif(key<a[mid]):
high=mid-1
else:
low=mid+1
return -1
n=int(input("enter the no of element:"))
a=[i for i in range(n)]
for i in range(0,n):
a[i]=int(input("enter the array element:"))
k=int(input("Enter the key element to be searched:"))
position=binary_search(a,n,k)
if(position!=-1):
print ("Searching value present in position: ",(position+1))
else:
print ("Searching value not present")
9
Sample Input/Output:
enter the no of element: 5
enter the array element: 10
enter the array element: 20
enter the array element: 30
enter the array element: 40
enter the array element: 50
Enter the key element to be searched: 30
Searching value present in position: 3
Result:
Thus a python program to search an element using Binary search technique was created
and executed successfully
10
SELECTION SORT
Aim:
Algorithm:
Program:
def selectionSort(a):
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i]>a[j]:
temp=a[j]
a[j]=a[i]
a[i]=temp
print("\nSorted Elements are:")
print(a)
print("SELECTION SORT:")
a=[]
#Reading input
n=int(input("Enter no. of elements:"))
for i in range(0,n):
11
num=int(input("enter the list element:"))
a.append(num)
print ("\nOriginal list:",a)
selectionSort(a) #calling to the function
Sample Input/Output:
SELECTION SORT:
Enter no. of elements:5
enter the list element:432
enter the list element:575
enter the list element:343
enter the list element:78
enter the list element:45
Result:
Thus the Python Program to perform selection sort is successfully executed and the
output is verified.
12
INSERTION SORT
Aim:
Algorithm:
1. Start
2. Get the elements from the user
3a. The second element in the list is compared with the elements that appear
before it (only first element in this case).
3b. If the second element is smaller than first element, second element is
inserted in the position of first element. After first step, first two elements of an
array will be sorted.
3c. Pick next element
4. Repeat step 3 until all the elements in the list is sorted
5. Stop
Program:
def insertion(a):
for i in range(0,len(a)):
currentvalue=a[i]
position=i
while position>0 and a[position-1]>currentvalue:
a[position]=a[position-1]
position=position-1
a[position]=currentvalue
print ("Insertion list",a)
13
a=[] #define empty list
print ("INSERTION SORT")
n=int(input("Enter the upper limit:"))
for i in range (n):
a.append(int(input()))
insertion(a)
Sample Input/Output:
Enter the upper limit:5
25
Insertion list [25]
12
Insertion list [12, 25]
65
Insertion list [12, 25, 65]
5
Insertion list [5, 12, 25, 65]
76
Insertion list [5, 12, 25, 65, 76]
Result:
Thus the Python program to perform insertion sort is successfully executed and the
output is verified.
14
MERGE SORT
Aim:
Algorithm:
15
Program:
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
nlist[k]=lefthalf[i]
i=i+1
k=k+1
nlist[k]=righthalf[j]
j=j+1
16
k=k+1
print("Merging ",nlist)
a=[]
#Reading input
for i in range(0,n):
a.append(num)
mergeSort(a)
Sample Input/Output:
Merge Sort
Splitting [678]
Merging [678]
17
Splitting [432]
Merging [432]
Splitting [776]
Merging [776]
Splitting [244]
Merging [244]
Splitting [566]
Merging [566]
Splitting [240]
Merging [240]
Splitting [732]
Merging [732]
Result:
Thus the Python program to perform merge sort is successfully executed and the
output is verified.
18
FIRST N PRIME NUMBERS
Aim:
To write a Python program to find first n prime numbers.
Algorithm:
1. Read the value of n
2. for num in range(0,n + 1), perform the following
3. if num%i is 0 then break else print the value of num
4. Repeat step 3 for i in range(2,num)
Program:
Sample Input/Output:
19
Prime number: 7
Prime number: 11
Prime number: 13
Prime number: 17
Prime number: 19
Result:
Thus the Python Program to find the first n prime numbers is executed successfully and
the output is verified.
20
MATRIX MULTIPLICATION
Aim:
To write a Python program to multiply matrices.
Algorithm:
Program:
21
Sample Input/Output:
Result:
Thus a Python Program to multiply matrices is executed successfully and the output
is verified.
22
PROGRAMS THAT TAKE COMMAND LINE ARGUMENTS
(WORD COUNT)
Aim:
To write a Python program to take command line arguments(word count)
Algorithm:
1. Start
2. Take the file name from the user
3. Read each line from a file and split a lines to form a list of words
4. Find the length of items in a list and print it
5. Stop
Program:
import sys
print("\n\n\t Script Name : ",sys.argv[0])
print("\n")
le=len(sys.argv)
for i in range(1,le):
print("\t Word : ",i," : ", sys.argv[i])
print("\n\n\t Word Count : ", len(sys.argv)-1)
23
Sample Input/Output:
Result:
Thus a Python Program for word count was created and executed successfully.
24
FIND THE MOST FREQUENT WORDS
IN A TEXT READ FROM A FILE
Aim:
To write a Python program to find the most frequent words in a text read
from a file.
Algorithm:
1. Start
4. For each line from the file and split the line to form a list of words in
line_word.
5. Use a for loop to traverse through the words in the list and another for loop
6. Check if the letter provided by the user and the letter encountered over
7. Print the word and the frequency of occurrence of the word. Which having
highest count value.
25
Program:
file = open("fileex.txt","r")
frequent_word = ""
frequency = 0
words = []
for line in file:
line_word = line.lower().split(" ");
for w in line_word:
words.append(w);
for i in range(0, len(words)):
count = 1;
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
if(count > frequency):
frequency = count;
frequent_word = words[i];
print("Most repeated word: " + frequent_word)
print("Frequency: " + str(frequency))
file.close();
26
Sample Input/Output:
Frequency: 12
Result:
Thus a Python to find the most frequent words in a text read from a file was created
and successfully.
27
SIMULATE ELLIPTICAL ORBITS IN PYGAME
Aim:
Algorithm:
1. Import the required packages
2. Set up the colours for the elliptical orbits
3. Define the parameters to simulate elliptical orbits
4. Display the created orbits
Program:
import pygame
import math
import sys
pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
xRadius = 250
yRadius = 100
for degree in range(0,360,10):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
screen.fill((0, 0, 0))
28
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)
Sample Input/Output:
Result:
Thus a Python to find the most frequent words in a text read from a file was created
and successfully.
29
SIMULATE BOUNCING BALL USING PYGAME
Aim:
To write a Python program to bouncing ball in Pygame.
Algorithm:
1. Import the required packages.
2. Define the size of the window and its background color and speed of the ball
movement
3. Invoke the ball image file.
4. Run the script to animate ball.
Program:
import sys
import pygame
pygame.init()
size = width, height = 800, 600
speed = [1, 1]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load('ball.png')
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(black)
screen.blit(ball, ballrect)
pygame.display.flip()
30
Sample Input/Output:
Result:
Thus a Python to find the most frequent words in a text read from a file was created and
successfully
31