0% found this document useful (0 votes)
76 views37 pages

Ge8161-Lab Programs

The document provides Python source code for 12 examples of common algorithms and problems. The examples include computing the greatest common divisor (GCD) of two numbers, finding the greatest of three numbers, calculating the sum of integers from 1 to n, determining the sum of the digits of a number, and more. For each example, the source code is provided along with sample input/output showing the code running. The examples cover topics like recursion, searching/sorting algorithms, and string/number problems.
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)
76 views37 pages

Ge8161-Lab Programs

The document provides Python source code for 12 examples of common algorithms and problems. The examples include computing the greatest common divisor (GCD) of two numbers, finding the greatest of three numbers, calculating the sum of integers from 1 to n, determining the sum of the digits of a number, and more. For each example, the source code is provided along with sample input/output showing the code running. The examples cover topics like recursion, searching/sorting algorithms, and string/number problems.
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/ 37

Ex:1 Compute the GCD of two numbers.

Source Code:

def computegcd(x, y):

# choose the smaller number

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

n1 = int(input("Enter first number: "))

n2 = int(input("Enter second number: "))

print("The G.C.D. of", n1,"and", n2,"is", computegcd(n1, n2))

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/gc.py',
wdir='C:/Users/admin/.anaconda/navigator')

Enter first number: 23

Enter second number: 21

The G.C.D. of 23 and 21 is 1


Ex:2 Greatest of three numbers.

Source Code:

a=int(input("enter a"))

b=int(input("enter b"))

c=int(input("enter c"))

if a>b and a>c:

print(a,"is Big")

elif b>c:

print(b,"is Big")

else:

print(c,"is Big")

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/ex2.py',
wdir='C:/Users/admin/.anaconda/navigator')

enter a 12

enter b2

enter c3

12 is Big
Ex:3 Find the sum 1+2+……+n

Source Code:
n=int(input("enter n"))

s=0

for i in range(0,n):

s=s+i

print("Sum=",s)

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/sum.py',
wdir='C:/Users/admin/.anaconda/navigator')

enter n 10

Sum= 45
Ex:4 Sum of the digits of a number

Source Code:
n=int(input("enter n"))

s=0

while n>0:

r=n%10

s=s+r

n=n/10

print("Sum of digits=",int(s))

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/sum.py',
wdir='C:/Users/admin/.anaconda/navigator')

enter n 252

Sum of digits= 9
Ex:5 Find the square root of a number (Newton’s method)

Source Code:
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
n=int(input("enter n"))
howmany=int(input("enter howmany iterations"))
print(newtonSqrt(n,howmany))

OUTPUT
enter n 10
enter howmany iterations3
3.162319422150883
>>>
Ex:6 Factorial of a number (Iteration and Recursion)
Source Code: (iteration)
n=int(input("enter n"))
f=1
for i in range(1,n+1):
f=f*i
print("Factorial=",f)

OUTPUT
runfile('C:/Users/admin/.anaconda/navigator/sum.py',
wdir='C:/Users/admin/.anaconda/navigator')
enter n 3
Factorial= 6
Source Code: (Recursion)
def fact(n):
if(n==0):
return (1)
else:
f=n*fact(n-1)
return (f)
n=int(input("enter n"))
print("Factorial=",fact (n))

OUTPUT
runfile('C:/Users/admin/.anaconda/navigator/sum.py',
wdir='C:/Users/admin/.anaconda/navigator')
enter n 3
Factorial= 6
Ex:7 Fibonacci Series

Source Code:

n=int(input("enter n"))
a=0
b=1
print("Series is")
print(a)
print(b)
for i in range(1,n+1):
c=a+b
a=b
b=c
print(c)
OUTPUT
enter n 8
Series is
0
1
1
2
3
5
8
13
21 34
Ex:8 Tower of Hanoi
Source Code:

def moveTower(height,fromPole, toPole, withPole):

if height >= 1:

moveTower(height-1,fromPole,withPole,toPole)

moveDisk(fromPole,toPole)

moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):

print("moving disk from",fp,"to",tp)

moveTower(3,"A","B","C")

OUTPUT
runfile('C:/Users/admin/.anaconda/navigator/toh.py',wdir='C:/Users/admin/.anacon
da/navigator')
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
Ex:9 Find the Exponentiation

Source Code :

import math
x=int(input("enter x"))
y=int(input("enter y"))
print ('power',math.pow(x,y))

OUTPUT
>>> runfile('C:/Users/admin/p.py', wdir='C:/Users/admin')
enter x 5
enter y2
power 25.0
>>>
Ex:10 Reverse of a given number
Source Code:

n = int(input("Enter a number: "))


s=0
while n>0:
r=n%10
s=s*10+r
n=n//10
print("Reverse=",int(s))

OUTPUT
runfile('C:/Users/admin/.spyder-py3/temp.py', wdir='C:/Users/admin/.spyder-py3')
Enter a number: 153
Reverse= 351
Ex:11 Swap two variables with/without using temporary
variable
Using Temporary Variable
Source Code:
x = int(input("Enter a number: "))
y=int(input("enter another number"))
print("Before swapping x=",x,"y=",y)
t=x
x=y
y=t
print("After swapping x=",x,"y=",y)

OUTPUT
runfile('C:/Users/admin/.spyder-py3/temp.py', wdir='C:/Users/admin/.spyder-py3')
Enter a number: 12
enter another number25
Before swapping x= 12 y= 25
After swapping x= 25 y= 12
Ex:12 (a) Swapping
Without Using Temporary Variable
Source Code:
x = int(input("Enter a number: "))
y=int(input("enter another number"))
print("Before swapping x=",x,"y=",y)
x,y=y,x
print("After swapping x=",x,"y=",y)

OUTPUT
runfile('C:/Users/admin/.spyder-py3/temp.py', wdir='C:/Users/admin/.spyder-py3')
Enter a number: 25
enter another number22
Before swapping x= 25 y= 22
After swapping x= 22 y= 25
Ex:12 (b) Guess an integer number in a range
Source Code:

import random

x = random.randrange(1, 201)

print(x)

guess = int(input("Please enter your guess: "))

if guess == x:

print("Hit!")

elif guess < x:

print("Your guess is too low")

else:

print ("Your guess is too high")

OUTPUT
>>> runfile('C:/Users/admin/.anaconda/navigator/gu.py',
wdir='C:/Users/admin/.anaconda/navigator')

158

Please enter your guess: 200

Your guess is too high

>>> runfile('C:/Users/admin/.anaconda/navigator/gu.py',
wdir='C:/Users/admin/.anaconda/navigator')

59

Please enter your guess: 20

Your guess is too low


EX: 13 Finding the Maximum in list

Source Code:

n=int(input("enter n"))
alist=[]
for i in range(n):
alist.append(input("Enter %dth element: "%i))
largest=alist[0]
for large in alist:
if large > largest:
largest=large
print(largest)

OUTPUT
enter n 5
Enter 0th element: 12
Enter 1th element: 50
Enter 2th element: 4
Enter 3th element: 70
Enter 4th element: 25
70
EX: 14 Find the sum of a list of numbers

Source Code:

n=int(input("enter n"))
alist=[]
s=0
for i in range(n):
alist.append(input("Enter %dth element: "%i))
s=s+int(alist[i])
print("Sum of list=",int(s))

OUTPUT
runfile('C:/Users/admin/.anaconda/navigator/sl.py',
wdir='C:/Users/admin/.anaconda/navigator')
enter n3
Enter 0th element: 12
Enter 1th element: 23
Enter 2th element: 23
Sum of list= 58
Ex: 15 Linear search

Source Code:

n = int(input("Enter the size of the list: "))


list = []
for i in range(n):
list.append(int(input("Enter %dth element: "%i)))
x = int(input("Enter number to search: "))
found = False
for i in range(len(list)):
if(list[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 the size of the list: 5
Enter 0th element: 7
Enter 1th element: 8
Enter 2th element: 9
Enter 3th element: 5
Enter 4th element: 6
Enter number to search: 7
7 found at 0th position
Ex:16 Binary search

Source Code:

def binary_search(list,t):
min = 0
max = len(list) - 1
while True:
if max < min:
return -1
mid = (min + max) // 2
if list[mid] < t:
min = mid + 1
elif list[mid] > t:
max = mid - 1
else:
return mid
n=int(input("Enter the size of the list: "))
list = []
for i in range(n):
list.append(int(input("Enter %dth element: "%i)))
t=int(input("enter the search element"))
pos=binary_search(list,t)
if pos==-1:
print("It is not found")
else:
print("element is found at position",pos)
OUTPUT
Enter the size of the list: 3

Enter 0th element: 9

Enter 1th element: 11

Enter 2th element: 25

enter the search element11

element is found at position 1


EX:17 Selection sort

Source Code:

n = input("Enter the size of the list: ")


source = []
for i in range(n):
source.append(input("Enter %dth element: "%i))
for i in range(len(source)):
mini = min(source[i:]) #find minimum element
min_index = source[i:].index(mini) #find index of minimum element
source[i + min_index] = source[i] #replace element at min_index with first
element
source[i] = mini #replace first element with min element
print source

OUTPUT
Enter the size of the list: 5
Enter 0th element: 4
Enter 1th element: 5
Enter 2th element: 8
Enter 3th element: 9
Enter 4th element: 7
[4, 5, 7, 8, 9]
EX:18 Insertion Sort
Source Code:

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
n = input("Enter the size of the list: ")
n=int(n)
alist = [ ]
for i in range(n):
alist.append(input("Enter %dth element: "%i))
insertionSort(alist)
print(alist)
OUTPUT
Enter the size of the list: 5
Enter 0th element: 7
Enter 1th element: 8
Enter 2th element: 4
Enter 3th element: 3
Enter 4th element: 2
['2', '3', '4', '7', '8']
EX:20 Finding N prime numbers

Source Code:

num=1
limit = int(input("Enter the ending number:"))
for i in range (1, limit+1,1):
count=0
for j in range (1, (num+1), 1):
rem = num%j
if (rem==0):
count = count+1
if (count==2):
print (num)
else:
i = i-1
num=num+1

OUTPUT
Enter the number: 15
2
3
5
7
11
13
EX:21 Check whether the given string is Palindrome or not

Source Code:

str=input("Enter string:")

if(str==str[::-1]):

print("The string is a palindrome")

else:

print("The string isn't a palindrome")

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/pal.py',
wdir='C:/Users/admin/.anaconda/navigator')

Enter string:madam

The string is a palindrome

runfile('C:/Users/admin/.anaconda/navigator/pal.py',
wdir='C:/Users/admin/.anaconda/navigator')

Enter string:python

The string isn't a palindrome


EX:22 Multiply two matrices

Source Code:

matrix1 = [[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]
matrix2 = [[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]]
rmatrix = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
rmatrix[i][j] += matrix1[i][k] * matrix2[k][j]
for r in rmatrix:
print(r)

OUTPUT
[32, 38, 44, 50]
[68, 83, 98, 113]
[104, 128, 152, 176]
EX:23 Addition of two matrices

Source Code:

n=3

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[5,8,1],

[6,7,3],

[4,5,9]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]

# adds the matrices

# iterate through rows

for i in range(len(X)):

# iterate through columns

for j in range(len(X[0])):

result[i][j] = X[i][j] + Y[i][j]

for r in result:

print(r)

OUTPUT

[17, 15, 4]
[10, 12, 9]

[11, 13, 18]

>>>
EX:24 Transpose of a Matrix

Source Code:

Matrix1 = [[1, 2, 3], [4, 5, 6],[7, 8, 9]]

Result = [[0,0,0],[0,0,0],[0,0,0]]

# iterate through rows

for i in range(len(Matrix1)):

# iterate through columns

for j in range(len(Matrix1[0])):

Result[j][i] = Matrix1[i][j]

print(‘Result = ‘)

for r in Result:

print(r)

OUTPUT

Input 1:

matrix1 = [[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]

Output 1:

Result = [[1, 4, 7],


[2, 5, 8],
[3, 6, 9]]
EX:25 Programs that take command line arguments (word count)

Source Code:

import sys

def word_count(str):

counts = dict()

str1=' '.join(str)

words = str1.split()

for word in words:

if word in counts:

counts[word] += 1

else:

counts[word] = 1

return counts

print( word_count(sys.argv[1:]))

OUTPUT
EX:26 Program that take command line arguments(average of three
numbers)

Source Code:

import sys

a=int(sys.argv[1])

b=int(sys.argv[2])

c=int(sys.argv[3])

avg=a+b+c//3

print("Average=",avg)

OUTPUT
EX:27 Program to print the mobile number for the given name
using dictionaries

Source Code:

Nameno = {"Ram":"9842054111", "Ravi":"9003059112",


"amudha":"9003044885"}

print(Nameno["Ram"])

print(Nameno.get("amudha"))

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/dic.py',
wdir='C:/Users/admin/.anaconda/navigator')

9842054111

9003044885
EX:28 Find the most frequent words in a text read from a file

Source Code:

import re
import string
frequency = {}
document_text = open('a.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print (words, frequency[words])
OUTPUT Have to create a.txt
rama
uma
kala
kiruba
raji
>>> runfile('C:/Users/admin/fcf.py', wdir='C:/Users/admin')
rama 1
uma 1
kala 1
kiruba 1
raji 1
EX:29 Copy the contents of one file to another file

Source Code:

with open("D:\\a.txt") as f:
with open("D:\\b1.txt", "w") as f1:
for line in f:
f1.write(line)
print("Contents are copied")

OUTPUT

runfile('C:/Users/admin/.anaconda/navigator/copy.py',
dir='C:/Users/admin/.anaconda/navigator')

Contents are copied

Content of file “a.txt”

RMK group of Engineering Colleges

Imparting Quality Education

Content of file “b.txt”

RMK group of Engineering Colleges

Imparting Quality Education


Ex:30

Simulation of Elliptical Objects

Source Code:

import math
import random
import pygame

class Particle ():


def __init__ (self, x, y, colour=0x000000):
self.x = x
self.y = y
self.vx = 0
self.vy = 0
self.colour = colour

def apply_gravity (self, target):


"""Accelerates the particle towards some mass at target."""
dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2 #distance squared
#g = G*m/dsqd * normalized (self - target)

if dsqd == 0:
return #division by zero is bad!

self.vx += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5


self.vy += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5

def update (self):


self.x += self.vx
self.y += self.vy

pygame.init()
window = pygame.display.set_mode ((600, 400))
main_surface = pygame.Surface ((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, 0xFFFFFF, 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):


p.vx = i / 100

while (True):
# main_surface.fill(0x000000)
pygame.draw.circle (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)

for p in particles:
p.apply_gravity (earth)
p.update ()
pygame.draw.circle (main_surface, p.colour, (int (p.x), int (p.y)), 5, 2)

window.blit(main_surface, (0, 0))


pygame.display.flip()

OUTPUT
Ex:31
Simulation of Bounding Ball
Source Code:

import sys

import pygame

pygame.init()

size = width, height = 320, 240

speed = [2, 2]

black = 0, 0, 0

screen = pygame.display.set_mode(size)
ball = pygame.image.load("C:\\Users\\admin\\Desktop//bi.jpg")

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()

OUTPUT

You might also like