Professional Documents
Culture Documents
BACHELOR OF ENGINEERING
FIRST SEMESTER
(Regulation 2017)
GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING
LAB MANUAL
OBJECTIVES
LIST OF PROGRAMS
PLATFORM NEEDED
OUTCOMES
TOTAL: 60 PERIODS
CONTENTS
a=5
b=6
print (a+b)
a=int(input("enter a value"))
b=int(input("enter a value"))
c=a * b
print("Multiplication of ", a, "x", b,"is", c)
N=int(input("enter value"))
fact=1
i=1
while i<=N :
fact=fact * i
i=i+1
print(" Factorial of ",N, " is ", fact)
N=int(input("enter a value"))
c=N % 2
if c == 0 :
print (" Given " , N, ". is EVEN")
else :
print( " Given " ,"N", "is ODD")
def ODD () :
# function block starts ---------------- single comment line
list= [4, 2, 8, 9, 3, 7]
list1=[]
j=0
for i in list :
if i % 2 != 0 :
list1.append(i)
j=j+1
for i in list1 :
print( i)
ODD ()
Ex. No 1 COMPUTE THE GCD OF TWO NUMBERS.
Aim:
Algorithm
Expected Output
C:\Python36-32\mypgm>ex1.py
enter first value12
enter second value20
The GCD of 12 , 20 is 4
Ex. No 2 FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S METHOD)
Aim
Algorithm
Pseudocode
Expected Output
C:\Python36-32\mypgm>a2.py
Newton's Method.
enter a value16
Square root of 16 is= 4.0
Ex. No 3 EXPONENTIATION (POWER OF A NUMBER)
Aim
Algorithm
Expected Output
Enter base: 10
Enter exponential value: 5
Result: 100000
Ex. No 4a FIND THE MAXIMUM OF A LIST OF NUMBERS
Aim
Algorithm
1. Initialize a List
2. Read the Number of Elements
3. Read the List values one by one
4. Set Max = first element of the list
5. Compare Max with List elements
6. If Max< List element
7. Set Max= List element
8. Continue the step 5 until reach the end of the List
9. Print the Max
Pseudocode :
def MaxList():
list1=[]
N=int(input( ))
for i in range (0,N):
x=int(input( ))
list1.append(x)
Max=list1[0]
print(Max)
j=1
for condition :
if condition :
statement
print(" The Maximum Element in the List is ",Max)
MaxList()
Expected Output
Aim
Algorithm
1. Initialize a List
2. Read the Number of Elements
3. Read the List values one by one
4. Set Dup = first element of the list
5. Compare Dup with List elements
6. If Dup = List element
7. Delete the List element
8. Continue the step 5 until the end of the List is reached
9. Print the duplicate List Elements
Pseudocode :
def DupList():
list1=[]
Dup = Set()
for val in list1:
if val not seen
output.append(val)
seen.add(val)
return output
list1=[]
result=DupList(val)
print(result)
Expected Output:
[5,1,4]
Ex. No 5a LINEAR SEARCH
Aim
Algorithm
Linear Search
Pseudocode:
def LS() :
listA=
flag=
N=
print("Enter values one by one")
for i in
a=
listA .
print(listA)
key=
for
if :
flag
if
print()
else:
printf()
LS()
Expected Output
C:\Python36-32\mypgm>a1.py
enter no.of values4
Enter values one by one
enter value11
enter value22
enter value33
enter value44
[11, 22, 33, 44]
enter key value22
22 is present in the List at position 2
Ex. No 5b BINARY SEARCH
Aim
Algorithm
Binary Search
5. Continue the steps 3 & 4 until the element found or reach the end of the list
6. Initialize a list ( elements in sorted order)
7. Call BS() with name of list & key value : BS(alist,key)
8. Print the result
Pseudocode:
def binarySearch(alist, key) :
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = ( )//2
if condition :
statement
elif condition :
statement
else:
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
x=binarySearch(testlist, 3)
print(x)
y=binarySearch(testlist, 13)
print(y)
Expected Output
False
Element Found 13
True
Ex No : 6a SELECTION SORT
Aim
Algorithm
Pseudocode
def selectionSort(alist):
for i in range(len(alist) , , ,):
Initialize positionOfMax as zero
for location in range( ):
if alist[location]>alist[positionOfMax]:
Equate positionOf Max and location
Swap the values
temp = alist[i]
alist[i] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [ , , , ]
Call selectionSort( )
print( )
Expected Output:
alist = [17, 20, 26, 31, 44, 54, 55, 77, 93]
Ex No : 6b INSERTION SORT
Aim
Algorithm
Pseudocode
def insertionSort(alist):
for i in range():
Equate currentvalue with alist[i]
Equate position and index
while pos>0 and alist[pos-1]>currentvalue:
alist[pos]=alist[pos-1]
Decrement pos
alist[position]=currentvalue
alist = [ , , , ]
call insertionSort( )
print( )
Expected Output:
alist = [17, 20, 26, 31, 44, 54, 55, 77, 93]
Ex No : 7a MERGE SORT
Aim
Algorithm
Pseudocode
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Ex. No 8 FIRST N PRIME NUMBERS
Aim
Algorithm
Pseudocode:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if ( ) == 0:
break
else:
print(num)
Expected Output
Enter lower range: 2
Enter upper range: 10
Prime numbers between 1 and 25 are: 2 3 5 7
Ex No : 9 MATRIX MULTIPLICATION
Aim
Algorithm
Matrix-Multiply(A, B)
1. Input two matrixes.
2. Output Output matrix C.
3. Complexity O(n^3)
4. if columns [A] ≠ rows [B]
then error "incompatible dimensions"
5. else
for i =1 to rows [A]
for j = 1 to columns [B]
C[i, j] =0
for k = 1 to columns [A]
C[i, j]=C[i, j]+A[i, k]*B[k, j]
6. return C
Pseudocode
Expected Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Ex No : 10 COMMAND LINE ARGUMENTS – WORD COUNT
Aim
To write a python program to perform count of the number of words using command
line arguments.
Algorithm
1. Start the program
2. Open the file by entering the name in read mode
3. Using For loop find the split point using a space.
4. Count the number of words in the file at split points.
5. Display the count of words
6. Terminate the loop and the program.
Pseudocode
# Command Line Arguments - find word count in a file
fname = input( filename)
initialize num_words=0
with open(fname , r) as file:
for loop:
words = line.split()
num_words += len(words)
print (num_words)
Expected Output:
Enter file name: data1.txt
Number of words:
2
Enter file name: data2.txt
Number of words:
5
Ex No : 11 FIND FREQUENCY OF WORDS
Aim
To write a python program to find the frequency of words using python file
programming.
Algorithm
1.Algorithm to count the frequency of occurrence
2.import re and string packages
3.open the file in read mode
4.read the text string in the document
5. Match the words with the pattern of test string
6.Using for loop count the frequency of words
7. Increment the frequency count if pattern occurs for second time.
8. Display the frequency count
9.Terminate the loop and the program.
Pseudocode
# Count frequency of word in a file
import re and string
frequency = {}
document_text = open(filename, 'r')
text_string = document_text.read()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for loop match pattern:
count = frequency and get(word,0)
increment the count
frequency_list = frequency.keys()
for loop frequency_list:
print frequency of words
Expected Output:
before 2
battle 1
field 1
all 2
any 1
altogether 1
ago 1
advanced 1
add 1
above 1
PYGAME INSTALLATION
To Install Pygame Module
Steps:
Collecting pygame
C:\Python36-32\Scripts\pygame-1.9.3>cd examples
C:\Python36-32\Scripts\pygame-1.9.3\examples>aliens.py
C:\Python36-32\Scripts\pygame-1.9.3\examples>
Do Yourself
Aim
To write a python program to simulate the Elliptical orbits using Pygame in python
programming.
Algorithm
Pseudocode
import pygame
pygame.init()
screen = pygame.display.set_mode( )
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.circle(screen, (color coordinates), [screen coordinates], size, radius)
pygame.draw.ellipse(screen, (color coordinates), [Screen Coordinates], orbits)
pygame.display.flip()
Expected Output:
Ex No : 13 SIMULATE BOUNCING BALL
Aim
To write a python program to simulate the bouncing Ball using Pygame in python
programming.
Algorithm
1. Import system,pygame
2. Initialize the pygame
3. Set the initial value of the variables.
4. Set the screen Display mode.
5. Load the ball image to the python program.
6. Set the gravity and horizontal acceleration
7. Set the vertical and Horizontal Speed.
8. Initialize the clock timer.
9. Using While loop Make the clock to tick.
10.Using While loop set the events.
11.If event type = QUIT then Quit Pygame.
12.Else set the keyboard controls UP , DOWN , LEFT , RIGHT for ball movement
13.Set the screen blit coordinates.
14.Update or refresh the screen.
15. Terminate the pygame.
Pseudocode
import sys,pygame
pygame.init()
… variables…
set the screen display mode with size
load the ball into the program
set the gravity acceleration
set the horizontal acceleration to zero
initialize the vertical speed to zero
initialize the horizontal speed to zero
clock = pygame.time.Clock()
While Loop:
Clock is ticking
Set the keyboard controls UP , DOWN , LEFT , RIGHT
screen.blit(ball, (x, y))
pygame.display.update()
Expected Output:
Viva Question
Ex No : 2
#Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# uncomment to take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Ex No : 3
# Compute exponentiation i.e. power of a number
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
print("Result:",power(base,exp))
Ex No : 4a
a=[]
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
Ex No : 4b
def remove_duplicates(values):
output = []
seen = set()
output.append(value)
seen.add(value)
return output
values = [5, 5, 1, 1, 2, 3, 4, 4, 5]
result = remove_duplicates(values)
print(result)
Ex No : 5A
#Linear search
list_of_elements = [4, 2, 8, 9, 3, 7]
found = False
for i in range(len(list_of_elements)):
if(list_of_elements[i] == x):
found = True
break
if(found == False):
Ex No : 5B
# binary search
# stepwise explanatino
#http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearc
h.html
first = 0
last = len(alist)-1
found = False
if alist[midpoint] == item:
found = True
print("Element Found",item)
else:
last = midpoint-1
else:
first = midpoint+1
return found
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
Ex No : 6A
#Selection sort
# Stepwise explanation
#http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSo
rt.html
def selectionSort(alist):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
Ex No : 6B
# Insertion Sort
#http://interactivepython.org/courselib/static/pythonds/SortSearch/TheInsertionSor
t.html
def insertionSort(alist):
currentvalue = alist[index]
position = index
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)
Ex No: 7a
#http://interactivepython.org/courselib/static/pythonds/SortSearch/TheMergeSort.h
tml
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
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)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Ex No : 8
upper = 1000
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Ex No:9
#Matrix Multiplication
# 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]]
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)
Ex No : 10
# data1.txt
# data2.txt
fname = input("Enter file name: ")
num_words = 0
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Ex No:11
# test.txt
import re
import string
frequency = {}
text_string = document_text.read().lower()
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
Ex No:12
import pygame
pygame.init()
done = False
if event.type == pygame.QUIT:
done = True
pygame.display.update()
pygame.display.flip()
Ex No:13
import pygame
pygame.init()
done = False
if event.type == pygame.QUIT:
done = True
pygame.draw.circle(screen, (255,255,255), [100, 80], 10, 0)
pygame.display.update()
pygame.display.update()
pygame.display.update()
pygame.display.update()
pygame.display.update()
pygame.display.update()
pygame.display.update()
pygame.display.update()
if event.type == QUIT:
pygame.quit()
sys.exit()