Exercise 1. Compute the GCD of two numbers.
Aim: To Compute the GCD of two number using Python.
Algorithm:
Start
Read num1, num2 to find the GCD
If x>y
o Smaller = y
o Else
o Smaller = x
For i - smaller+1
o If x%i==0 and y%i==0
o Return gcd
Call fun and Print gcd(num1,num2)
Stop
Program:
def GCD(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
num1 = 20
num2 = 10
print("The GCD. of", num1,"and", num2,"is", GCD(num1, num2))
Output:
The [Link] 20 and 10 is 10
Exercise 2 Find the square root of a number (Newton„s method)
Aim: To find the squareroot of a number using python.
Algorithm:
Start
Read the input from n,a
Approx = 0.5*n
For i upto range a
o Betterapprox = 0.5*(approx+n/approx)
o Approx = betterapprox
Return betterapprox
Call the function and print newtonsqrt(n,a)
Stop
Program:
def newtonSqrt(n, a):
approx = 0.5 * n
for i in range(a):
betterapprox = 0.5 * (approx +n/approx)
approx = betterapprox
return betterapprox
print(newtonSqrt(10, 3))
print(newtonSqrt(10, 5))
print(newtonSqrt(10, 10))
Output:
3.162319422150883
3.162277660168379
3.162277660168379
Exercise 3. Exponentiation (power of a number)
Aim: To find the exponentiation using python programming
Algorithm:
Start
Read base value number in base
Read exponent value number in exp
If exp is equal to 1
o Return base
If exp is not equal to 1
o Return (base*powerexp(base, exp-1)
Call function Print the result
Stop
Program:
def powerexp(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*powerexp(base,exp-1))
base=int(input("Enter base Value: "))
exp=int(input("Enter exponential Value: "))
print("Result:",powerexp(base,exp))
Output:
Enter base Value: 5
Enter exponential Value: 3
Result: 125
Exercise 4: Find the maximum of a list of numbers
Aim: To find the maximum of a list of numbers using python.
Algorithm:
Start
Read number of elements of the list
Using loop until n-1
o Read thr element user given in b
Append all the elements in a
Repeat 4th step upto n-1
Sorting a
Print the maximum of a list of number
Stop
Program:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
[Link](b)
[Link]()
print("Maximum of a List of Number is:",a[n-1])
Output:
Enter number of elements: 5
Enter element: 5
Enter element: 8
Enter element: 2
Enter element: 1
Enter element: 8
Maximum of a List of Number is: 24
Exercise [Link] search
Aim: To find the value using linear search in python program.
Algorithm:
Start
Read n elements to list
If I > n then go to step 7
If A[i] = x then go to step 6
Set I to I + 1
Go to step 2
Print elements x Found at index I And go to step 8
Print element not found
Stop
Program:
list_of_elements = [4, 2, 8, 9, 3, 7]
x = int(input("Enter number to search: "))
found = False
for i in range(len(list_of_elements)):
if(list_of_elements[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
4
4 is found at 0th position
Enter number to search
12
12 is not in the list
Aim: To find the value using binary search in python program.
Algorithm:
Start
Read the array elements
Find the middle element in the sorted list
Compare, the search element with middle element in the sorted list
If both are matching print “Item Has been found”
If the element also doesn‟t match with the search element, then print “Items
Not Found”
Stop
Program:
def binarysearch(myItem,myList):
found=False
bottom=0
top=len(myList)-1
while bottom<=top and not found:
middle=(bottom+top)//2
if myList[middle]==myItem:
found=True
elif myList[middle]<myItem:
bottom=middle+1
else:
top=middle-1
return found
numberList=[1,2,13,14,16,24,34,45,67,87]
item=int(input("what no looking for"))
isitFound=binarysearch(item,numberList)
if isitFound:
print("the number is in the list")
else:
print("the number is not in the list")
output:
what no looking for
13
The number is in the list
97
The number is not in the list
Exercise 6: Selection sort, Insertion sort
Aim: To sort list of elements using selection sort.
Algorithm:
Start
Read upper Limit n
Read n elements to the list
For I = I to len(sample)
o while(j <len(sample))
o Repeat the steps until condition satisfied
Call function Selsort() print the sorted elements.
Program:
array=[1,45,10,35,100,13,147,500,80]
size=len(array)
for i in range(0,size):
for j in range(i+1,size):
if array[j]<array[i]:
min=array[j]
array[j]=array[i]
array[i]=min
print(array)
output:
[1,10,13,35,45,80,100,147,500]
Aim: To sort list of elements using insertion sort.
Algorithm:
Start
Read upper Limit n
Read n elements to the list
For Index = 1 to len(sample)
o while(position>0 and lst[position-
1]>currentvalue)
o Repeat the steps until condition satisfied
Call function insertsort () print the sorted elements
Program:
def insertionsort(lst):
for index in range(1,len(lst)):
currentvalue=lst[index]
position=index
while position>0 and lst[position-1]>currentvalue:
lst[position]=lst[position-1]
position=position-1
lst[position]=currentvalue
lst=[54,26,93,17,77,31,44,55,20]
insertionsort(lst)
print(lst)
output:
[17 , 20 , 26 , 31 , 44 , 54 , 55 , 77 , 93]
Exercise 7: Merge sort
Aim: To sort list of elements using merge sort.
Algorithm
Start
Divide the arrays in left sub array & right sub array
Conquer by recursively sorting the two sub arrays
Combine the elements back in by merging the two sorted sub arrays
Call the results and print the arrays
Stop
Program:
a=[]
c=[]
n1=int(input("enter the no of element"))
for i in range(1,n1+1):
b=int(input("enter element"))
[Link](b)
n2=int(input("enter no of element"))
for i in range(1,n2+1):
d=int(input("enter element"))
[Link](d)
new=a+c
[Link]()
print("sorted list is",new)
output:
enter the no of element
3
13
11
4
Enter the no of element
2
14
2
Sorted list is
2 , 4 , 11, 13, 14
Exercise 8: First n prime numbers.
Aim: To write a program to find the prime number.
Algorithm:
[Link] in the upper limit for the range and store it in a variable.
2. Let the first for loop range from 2 to the upper limit.
3. Initialize the count variable to 0.
4. Let the second for loop range from 2 to half of the number (excluding 1 and the number itself).
5. Then find the number of divisors using the if statement and increment the count variable each time.
6. If the number of divisors is lesser than or equal to 0, the number is prime.
7. Print the final result.
8. Exit.
Program:
r=int(input("enter upper limit"))
for a in range(2,r+1):
k=0
for i in range(2,a//2):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
output:
enter upper limit10
2
3
5
7
Exercise 9. Multiply matrices
Aim: To Multiply Matrices using python.
Algorithm:
Start
Read matrix x and read matrix y
Loop for each row in matrix X
Loop for each columns in matrix Y
Initialize output matrix Result to 0. This loop will run for each rows of matrix X.
Multiply X[i][k] * Y[k][j] and this value to result[i][j]
Print Matrix Result
Stop
Program:
x=[[1,2,3],[4,5,6],[7,8,9]]
y=[10,11,12],[13,14,15],[16,17,18]]
result=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(y[0])):
for k in range(len(y)):
result[i][j] += x[i][k] * y[k] [j]
for r in result:
print(r)
Output:
[84 ,90, 96]
[201, 206, 231]
[318 ,342, 366 ]
Exercise 10: Programs that take command line arguments(word count)
Aim: To find the word and lines in command line arguments.
Algorithm:
Start
Add arguments to find the words and lines
Add file name as argument
Parse the arguments to get the values
Format and print the words
Stop
Program:
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = [Link]()
num_words += len(words)
print("Number of words:")
print(num_words)
Output:
Enter file name: [Link]
Number of words: 27
Exercise 11: Find the most frequent words in a text read from a file.
Aim: To find the most frequent words in a text read from a file.
Algorithm:
Start
Read the filename
Open the file
Read each line from the file to count the lowers and words
Split each line in to words and count them
Print the word and counts
Stop
Program:
fr = open("[Link]","r")
wordcount = {}
for word in [Link]().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in [Link]():
print(k, v)
[Link]()
Output:
To - 1
Find - 1
The - 1
Most-1
Frequent-1
Words-1
In-1
A-2
Text-1
Read-1
From-1
File-1
Exercise 12 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 math
import random
import pygame
class Particle ():
def __init__ (self, x, y, colour=0x000000):
self.x = x
self.y = y
[Link] = 0
[Link] = 0
[Link] = colour
def apply_gravity (self, target):
dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2
#g = G*m/dsqd * normalized (self - target)
if dsqd == 0:
return
[Link] += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5
[Link] += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5
def update (self):
self.x += [Link]
self.y += [Link]
[Link]()
window = [Link].set_mode((600, 400))
main_surface = [Link] ((600, 400))
colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555, 0x666666,
0x777777, 0x888888, 0x999999, 0xaaaaaa, 0xbbbbbb] + [0xFF0000,
0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888,
0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000]
#colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888,FFFFF,
0x808000, 0x008080, 0x800080, 0x800000]
particles = [Particle (200, 100, colours [i]) for i in range (20)]
earth = Particle (200, 200)
for i, p in enumerate (particles):
[Link] = i / 100
while (True):
# main_surface.fill(0x000000)
[Link] (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)
for p in particles:
p.apply_gravity (earth)
[Link] ()
[Link] (main_surface, [Link], (int (p.x), int (p.y)), 5, 2)
[Link](main_surface, (0, 0))
[Link]()
output:
Result:
Thus the Python Program to simulate elliptical orbits using Pygame is executed
successfully and the output is verified.
Exercise 13: 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 required variables
3. Define the screen space to display the bouncing balls in that space
Program: