0% found this document useful (0 votes)
1 views31 pages

Python Lab

The document outlines various Python programs for mathematical computations and algorithms, including finding the GCD of two numbers, calculating square roots using Newton's method, performing exponentiation, and searching for maximum values in a list. It also covers linear and binary search techniques, as well as sorting algorithms like selection sort, insertion sort, and merge sort. Additionally, it includes a program to find the first n prime numbers, demonstrating the implementation of these algorithms with sample inputs and outputs.

Uploaded by

r.balamurugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views31 pages

Python Lab

The document outlines various Python programs for mathematical computations and algorithms, including finding the GCD of two numbers, calculating square roots using Newton's method, performing exponentiation, and searching for maximum values in a list. It also covers linear and binary search techniques, as well as sorting algorithms like selection sort, insertion sort, and merge sort. Additionally, it includes a program to find the first n prime numbers, demonstrating the implementation of these algorithms with sample inputs and outputs.

Uploaded by

r.balamurugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

COMPUTE THE GCD OF TWO NUMBERS

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

# take input from the user


num = int(input("Enter a number: "))
print('The square root is' ,newtonSqrt(num))
Sample Input/Output
Enter a number: 50
The square root is 7.0710678118654755

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:

To write a Python program to find the exponentiation of a number.

Algorithm:

1. Define a function named power()


2. Read the values of base and exp
3. Use ‘if’ to check if exp is greater than 1 or not
i. exp is greater than 1, then return (base*power(base,exp-1))
ii. if exp is equal to 1, then return base
4. Print the result

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:

Thus the Python program to find the exponentiation of a number is executed


successfully and the output is verified.

3
FINDING THE MAXIMUM OF A LIST OF NUMBERS

Aim:

To write a Python Program to find the maximum from a list of numbers.

Algorithm:

1. Create an empty list named l


2. Read the value of n
3. Read the elements of the list until n
4. Assign l[0] as maxno
5. If l[i]>maxno then set maxno=l[i]
6. Increment i by 1
7. Repeat steps 5-6 until i<n
8. Print the value of maximum number

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:

1. Read n elements into the list


2. Read the element to be searched
3. Compare the search element with list element in sequence
4. if the search element found in the list display it position,
5. Else display element not found

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:

Enter no. of elements:5


enter the list element:COMPUTER
enter the list element:LAPTOP
enter the list element:CAR
enter the list element:BUS
enter the list element:MOBILE
Enter the key element to be searched:BUS
Search element BUS is found at possition: 4

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:

To write a Python Program to perform selection sort.

Algorithm:

1. Create a function named selectionSort


2. Read the input, going to be sorted
3. For i=1 to size of a list do the following
4. If a[i]>a[j], swap a[i] and a[j] values
5. Print the sorted list

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

Original list : [432, 575, 343, 78, 45]

Sorted Elements are:


[45, 78, 343, 432, 575]

Result:
Thus the Python Program to perform selection sort is successfully executed and the
output is verified.

12
INSERTION SORT

Aim:

To write a Python program to sort the elements using insertion sort.

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:

To write a Python program to sort the elements using Merge sort.

Algorithm:

1. Create a function named mergesort


2. Find the mid of the list
3. Assign lefthalf = alist[:mid] and righthalf = alist[mid:]
4. Initialise i=j=k=0
5. while i < len(lefthalf) and j < len(righthalf), perform the following
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
Increment i
else
alist[k]=righthalf[j]
Increment j
Increment k
6. while i < len(lefthalf),perform the following
alist[k]=lefthalf[i]
Increment i
Increment k
7. while j < len(righthalf), perform the following
alist[k]=righthalf[j]
Increment j
Increment k

8. Print the sorted list

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

while i < len(lefthalf) and j < len(righthalf):

if lefthalf[i] < righthalf[j]:

nlist[k]=lefthalf[i]

i=i+1

else:

nlist[k]=righthalf[j]

j=j+1

k=k+1

while i < len(lefthalf):

nlist[k]=lefthalf[i]

i=i+1

k=k+1

while j < len(righthalf):

nlist[k]=righthalf[j]

j=j+1

16
k=k+1

print("Merging ",nlist)

a=[]

#Reading input

n=int(input("Enter no. of elements:"))

for i in range(0,n):

num=int(input("enter the list element:"))

a.append(num)

mergeSort(a)

print(“Sorted List ”,a)

Sample Input/Output:

Merge Sort

Enter no. of elements:7

enter the list element:678

enter the list element:432

enter the list element:776

enter the list element:244

enter the list element:566

enter the list element:240

enter the list element:732

Splitting [678, 432, 776, 244, 566, 240, 732]

Splitting [678, 432, 776]

Splitting [678]

Merging [678]

Splitting [432, 776]

17
Splitting [432]

Merging [432]

Splitting [776]

Merging [776]

Merging [432, 776]

Merging [432, 678, 776]

Splitting [244, 566, 240, 732]

Splitting [244, 566]

Splitting [244]

Merging [244]

Splitting [566]

Merging [566]

Merging [244, 566]

Splitting [240, 732]

Splitting [240]

Merging [240]

Splitting [732]

Merging [732]

Merging [240, 732]

Merging [240, 244, 566, 732]

Merging [240, 244, 432, 566, 678, 732, 776]

Sorted List [240, 244, 432, 566, 678, 732, 776]

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:

n=int(input("Enter the limit:"))


for num in range(1,n): #iterate between 1 to n
for i in range(2,num): #iterate factors of the num
if num%i==0:
break
else:
print ("Prime number:",num)

Sample Input/Output:

Enter the limit:20


Prime number: 1
Prime number: 2
Prime number: 3
Prime number: 5

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:

1. Define two matrices A and B


2. Create a resultant matrix named ‘C’
3. for i in range(len(A)):
i. for j in range(len(B[0])):
a) for k in range(len(B))
b) C[i][j] += A[i][k] * B[k][j]
4. for r in C, print the value of r

Program:

A = [[1,2,3],[4 ,5,6],[3 ,2,1]]


# 3x4 matrix
B = [[5,8,1,2],[6,7,3,0],[4,5,9,1]]
# result is 3x4
C = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
for r in C:
print(r)

21
Sample Input/Output:

[29, 37, 34, 5]

[74, 97, 73, 14]

[31, 43, 18, 7]

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

2. Open a text file in read mode

3. Initialize frequent_word, frequency and words

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

to traverse through the letters in the word

6. Check if the letter provided by the user and the letter encountered over

iteration is equal and if they are, increment the word count

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:

Most repeated word: of

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:

To write a Python program to simulate elliptical orbits in Pygame.

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

You might also like