Valliammai Engineering College: Department of General Engineering
Valliammai Engineering College: Department of General Engineering
I SEMESTER
GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
Regulation – 2017
Prepared by
STUDENTSFOCUS.COM
SYLLABUS
LIST OF PROGRAMS
7. Merge sort
9. Multiply matrices
11. Find the most frequent words in a text read from a file
PLATFORM NEEDED
TOTAL: 60 PERIODS
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 2 of 45
INDEX
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 3 of 45
Ex. No: 1
AIM:
ALGORITHM :
Step 1: Start
Step 2: read two numbers to find the GCD n1,n2.
Step 3: rem=d1%d2
Step 4: while rem!=0
d1=d2
d2=rem
Rem=d1%d2
Step 5: print GCD is d2.
Step 6: Stop
PROGRAM/SOURCE CODE :
d1=int(raw_input("Enter a number:"))
rem=d1%d2
while rem!=0 :
d1=d2
d2=rem
rem=d1%d2
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 4 of 45
print "gcd of given numbers is : %d" %(d2)
OUTPUT :
RESULT:
Thus the program to find the GCD of two numbers is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 5 of 45
Ex. No: 2
AIM:
To write a python program to find the square root of a number (Newton’s method)
ALGORITHM :
Step 1: Define a function for Newton square root with two arguments.
Step 2: Assign the approximate value = 0.5*n.
Step 3: In each iteration, decide the range.
Step 4: Then calculate the approximate value.
Step 5: Return the approximate value.
Step 6: Finally print the values.
PROGRAM/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
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 6 of 45
Thus the program to find the square root (Newton’s method) is executed and the output is
obtained.
Ex. No: 3
EXPONENTIATION (POWER OF A NUMBER)
AIM:
ALGORITHM :
Step 1: Start.
Step 2: read base value
Step 3: Read exponent value.
Step 4: if base value is equal to one return base
Step 5: if base value is not equal to one return .
return(base*power(base,exp-1))
Step 6: print the result of program.
Step 7: Stop.
PROGRAM/SOURCE CODE:
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 :
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 7 of 45
Result: 9
RESULT:
Thus the program to find the exponentiation of a number is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 8 of 45
Ex. No: 4
AIM:
ALGORITHM :
Step 1: Start.
PROGRAM/SOURCE CODE :
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
OUTPUT :
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 9 of 45
Enter element:4
Largest element is:5
RESULT:
Thus the program to find the Maximum of a List of numbers is executed and the output is
obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 10 of 45
Ex. No: 5a
LINEAR SEARCH
AIM:
ALGORITHM :
Step 1: Start
Step 5: Search the element with using for loop until length of list
PROGRAM/SOURCE CODE :
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 11 of 45
OUTPUT :
Enter number to search: 90
found at 4th position
RESULT:
Thus the program to perform linear Search is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 12 of 45
Ex. No: 5b
BINARY SEARCH
AIM:
ALGORITHM :
Exit
Go to Step:1
Go to Step:2
Else:
Exit
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 13 of 45
PROGRAM/SOURCE CODE :
def Binary_search(arr,start_index,last_index,element):
mid =(int)(start_index+last_index)/2
if (element>arr[mid]):
start_index = mid+1
elif (element<arr[mid]):
last_index = mid-1
return mid
return -1
arr = [2,14,19,21,99,210,512,1028,4443,5110]
element = 4443
start_index = 0
last_index = len(arr)-1
found = Binary_search(arr,start_index,last_index,element)
if (found == -1):
else:
OUTPUT:
RESULT:
Thus the program to perform Binary Search is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 14 of 45
Ex. No: 6a
SELECTION SORT
AIM:
ALGORITHM:
Step 1: Read the number of elements for the list from the user.
Step 4: Using the swap method the elements are sorted accordingly.
PROGRAM/SOURCE CODE:
def selectionSort(nlist):
maxpos=0
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 15 of 45
OUTPUT:
[14, 21, 27, 41, 43, 45, 46, 57, 70]
RESULT:
Thus the program to perform Selection Sort is executed and the output is obtained.
Ex. No: 6b
INSERTION SORT
AIM:
ALGORITHM:
Step 1: Read the number of elements for the list from the user.
Step 5: If the condition is true swap the values by changing the position.
PROGRAM/SOURCE CODE:
def insertionSort(alist):
currentvalue = alist[index]
position = index
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 16 of 45
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 perform Insertion Sort is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 17 of 45
Ex. No: 7
MERGE SORT
AIM:
ALGORITHM:
if len(alist)>1:
mid = len(alist)//2
lefthalf=alist[:mid]
righthalf=alist[mid;]
PROGRAM/SOURCE CODE:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 18 of 45
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
alist[k]=lefthalf[i]
i=i+1
k=k+1
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 19 of 45
alist = []
n=int(input("Enter n:"))
for i in range(0,n):
mergeSort(alist)
print(alist)
OUTPUT :
Enter n:6
Enter numbers[0]: 45
Enter numbers[1]: 12
Enter numbers[2]: 34
Enter numbers[3]: 6
Enter numbers[4]: 8
Enter numbers[5]: 1
Splitting [45]
Merging [45]
Splitting [12]
Merging [12]
Splitting [34]
Merging [34]
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 20 of 45
Splitting [6, 8, 1]
Splitting [6]
Merging [6]
Splitting [8, 1]
Splitting [8]
Merging [8]
Splitting [1]
Merging [1]
Merging [1, 8]
Merging [1, 6, 8]
RESULT:
Thus the program to perform Merge Sort is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 21 of 45
Ex. No: 8
ALGORITHM:
Step1: Take in the upper limit for the range and store it in a variable.
Step 2: Let the first for loop range from 2 to the upper limit.
Step3: Initialize the count variable to 0.
Step4: Let the second for loop range from 2 to half of the number (excluding 1 and the number itself).
Step 5: Then find the number of divisors using the if statement and increment the count variable each
time.
Step 6: If the number of divisors is lesser than or equal to 0, the number is prime.
Step 7: Print the final result.
PROGRAM/SOURCE CODE:
i=1
x = int(input("Enter the number:"))
if (c==2):
print (i)
else:
k = k-1
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 22 of 45
i=i+1
OUTPUT:
RESULT:
Thus the program to find first n prime numbers is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 23 of 45
Ex. No: 9
MULTIPLY MATRICES
AIM:
ALGORITHM :
PROGRAM/SOURCE CODE :
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 24 of 45
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
for r in result:
print(r)
OUTPUT :
RESULT:
Thus the program to perform matrix Multiplication is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 25 of 45
Ex. No: 10
AIM:
ALGORITHM :
Step 1: Start
Step 6: Stop
PROGRAM/SOURCE CODE :
import sys
total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[0]))
print ("Second argument: %s" % str(sys.argv[1]))
print ("Third argument: %s" % str(sys.argv[2]))
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 26 of 45
OUTPUT :
RESULT:
Thus the program to count the words is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 27 of 45
Ex. No: 11
AIM:
To write a python program to find the most frequent words from a file.
ALGORITHM :
Step 5: Print the frequent words that are used in the file.
PROGRAM/SOURCE CODE :
N = 10
words = {}
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 28 of 45
OUTPUT :
RESULT:
Thus the program to find the most frequent words in a text is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 29 of 45
Ex. No: 12
AIM:
ALGORITHM :
Step 1: Import the necessary header files for the implementation of this pygame.
Step 2: Set the display mode for the screen using
screen=pygame.display.set_mode((700,700))
Step 3: Develop the balls with necessary colors.
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
Step 4: Set the radius for sun, moon and their orbit.
Step 5: Set the time for the pygame orbit clock=pygame.time.Clock()
Step 6: Update the earth position.
Step 7: Again update moon position based on earth position.
Step 8: Update the moon and earth angles.
Step 9: Reset the screen and draw the stars, sun, moon and the earth.
Step 10: Set the clock tick as (60) and exit.
PROGRAM/SOURCE CODE :
import pygame
import random
import math
pygame.init()
screen=pygame.display.set_mode((700,700))
white=(255,255,255)
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 30 of 45
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
sun_radius=50
center=(350,350)
earth_x=50
earth_y=350
earth_orbit=0
moon_orbit=0
clock=pygame.time.Clock()
running=True
stars=[(random.randint(0,699),random.randint(0,699)) for x in range(140)]
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
earth_x=math.cos(earth_orbit)*300+350
earth_y=-math.sin(earth_orbit)*300+350
moon_x=math.cos(moon_orbit)*50+earth_x
moon_y=-math.sin(moon_orbit)*50+earth_y
earth_orbit+=0.002
moon_orbit+=0.01
screen.fill(black)
for star in stars:
x,y=star[0],star[1]
pygame.draw.line(screen,white,(x,y),(x,y))
pygame.draw.circle(screen,yellow,center,sun_radius)
pygame.draw.circle(screen,blue,(int(earth_x),int(earth_y)),15)
pygame.draw.circle(screen,gray,(int(moon_x),int(moon_y)),5)
pygame.display.flip()
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 31 of 45
clock.tick(60)
pygame.quit()
OUTPUT :
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 32 of 45
RESULT:
Thus the simulation of elliptical curve orbit using pygame is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 33 of 45
Ex. No: 13
AIM:
PROGRAM/SOURCE CODE :
import pygame,sys,time
import random
frompygame.locals import *
from time import *
pygame.init()
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 34 of 45
windowSurface=pygame.display.set_mode((500,400),0,32)
pygame.display.set_caption("Bounce")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
info=pygame.display.Info()
sw=info.current_w
sh=info.current_h
y=0
direction=1
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface,GREEN,(250,y),13,0)
sleep(0.006)
y+=direction
if y>=sh:
direction=-1
elif y<=100:
direction=1
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 35 of 45
OUTPUT :
RESULT:
Thus the program to simulate bouncing ball using pygame is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 36 of 45
TOPIC BEYOND SYLLABUS
A1.TOWER OF HANOI
AIM:
ALGORITHM:
Step 3: Move a tower of height-1 to an intermediate pole, using the final pole.
Step 5: Move the tower of height-1 from the intermediate pole to the final pole using the original
pole.
OUTPUT:
moving disk from A to B
moving disk from A to C
moving disk from B to C
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 37 of 45
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
RESULT:
Thus the program for Tower of Hanoi scenario is executed and the output is obtained.
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 38 of 45
A2.PROGRAM TO FIND GIVEN NUMBER IS ARMSTRONG NUMBER OR NOT
ALGORITHM
1. Start
2. Declare variables
3. Read the Input number.
4. Calculate sum of cubic of individual digits of the input.
5. Match the result with input number.
6. If match, Display the given number is Armstrong otherwise not.
7. Stop
SOURCE CODE
num = 1634
order = len(str(num))
# initialize sum
sum = 0
temp = num
digit = temp % 10
temp //= 10
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 39 of 45
# display the result
if num == sum:
else:
OUTPUT
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 40 of 45
A3.BUBBLE SORT ALGORITHM
ALGORITHM
1. Start
2. Declare variables and create an array
3. Read the Input for number of elements and each element.
4. Develop a function bubblesort to sort the array
5. Compare the elements in each pass till all the elements are sorted.
6. Display the output of the sorted elements .
7. Stop
SOURCE CODE
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
exchanges = False
for i in range(passnum):
if alist[i]>alist[i+1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
passnum = passnum-1
alist=[20,30,40,90,50,60,70,80,100,110]
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 41 of 45
shortBubbleSort(alist)
print(alist)
OUTPUT
[20,30,40,50,60,70,80,90,100,110]
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 42 of 45
A4.PYTHON PROGRAM TO FIND THE SUM OF NATURAL NUMBERS UP TO N USING RECURSIVE
FUNCTION
ALGORITHM
1. Start
2. Declare variables and initializations
3. Read the Input variable.
4. Define recursive expression for computational processing.
5. Return the output of the calculations.
6. Stop
SOURCE CODE
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
num = 16
if num < 0:
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 43 of 45
else:
OUTPUT
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 44 of 45
VIVA QUESTIONS
1. What is Python?
2. What is the purpose of PYTHONPATH environment variable?
3. How Python is interpreted?
4. Is python a case sensitive language?
5. What are the supported data types in Python?
6. What are the built-in type does python provides?
7. What is namespace in Python?
8. What are Python's dictionaries?
9. How will you create a dictionary in python?
10. What is Expression?
11. What is module and package in Python?
12. Mention what are the rules for local and global variables in Python?
13. How will you convert a single character to its integer value in python?
14. What is the purpose of ** operator?
15. What is the purpose is of is operator?
16. How will you randomize the items of a list in place?
17. How will you capitalizes first letter of string?
18. What is function?
19. What are the types of function?
20. What is return type?
21. Mention the use of the split function in Python?
22. Explain what is Flash & its benefits?
23. What is File?
24. How to Read the file?
25. How to copy the data from one file to another file?
STUDENTSFOCUS.COM
LM- GE8161 [PSPPL] Page 45 of 45