[go: up one dir, main page]

0% found this document useful (0 votes)
222 views33 pages

Ge8161-Pspp Lab Manual

The document contains a syllabus and list of programs for a Python programming laboratory course, including programs to calculate the GCD of two numbers, find square roots and exponents, perform sorting and searching algorithms, and simulate physical systems like orbits and bouncing balls using Pygame.

Uploaded by

balakiruba
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)
222 views33 pages

Ge8161-Pspp Lab Manual

The document contains a syllabus and list of programs for a Python programming laboratory course, including programs to calculate the GCD of two numbers, find square roots and exponents, perform sorting and searching algorithms, and simulate physical systems like orbits and bouncing balls using Pygame.

Uploaded by

balakiruba
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/ 33

PARK COLLEGE OF TECHNOLOGY

Prema Ravi Nagar, Karumathampatti, Coimbatore - 641659

P A R K

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

I SEMESTER - R 2017

GE8161– PROBLEM SOLVING AND PYTHON

PROGRAMMING

LABORATORY MANUAL

Prepared by

Mrs.BALAKIRUBA.J, AP/CSE
SYLLABUS

GE8161 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LTPC


0042
OBJECTIVES:
▪ To write, test, and debug simple Python programs.
▪ To implement Python programs with conditionals and loops.
▪ Use functions for structuring Python programs.
▪ Represent compound data using Python lists, tuples, dictionaries.
▪ Read and write data from/to files in Python.

LIST OF PROGRAMS:
1. Compute the GCD of two numbers.
2. Find the square root of a number (Newton‘s method)
3. Exponentiation (power of a number)
4. Find the maximum of a list of numbers
5. Linear search and Binary search
6. Selection sort, Insertion sort
7. Merge sort
8. First n prime numbers
9. Multiply matrices
10. Programs that take command line arguments (word count)
11. Find the most frequent words in a text read from a file
12. Simulate elliptical orbits in Pygame
13. Simulate bouncing ball using Pygame

PLATFORM NEEDED
Python 3 interpreter for Windows/Linux

TOTAL: 60 PERIODS
INDEX

S.NO PROGRAM NAME PAGE NO

1 GCD Of Two Numbers 4

2 Square Root Of A Number (Newton’s Method) 6

3 Exponentiation Of A Number 8
(Power Of A Number)

4 Find The Maximum Of A List Of Numbers 10

5(a) Linear Search 12

5(b) Binary Search 14

6(a) Selection Sort 16

6(b) Insertion Sort 18

7 Merge Sort 20

8 First N Prime Numbers 22

9 Matrix Multiplication 24

10 Command Line Arguments ( Word Count ) 26

11 Frequent Words In A Text Read From A File 28

12 Simulation Of Elliptical Orbit Using Pygame 30

13 Simulation Of Bouncing Ball Using Pygame 32


Ex.No:1
GCD OF TWO NUMBERS
Date:

Aim:
To write a python program to find GCD of two numbers.

Algorithm:
Step 1: Start the program
Step 2: Read the value of a and b
Step 3: Calculate rem=a%b
Step 4: while(rem!=0)
a=b
b=rem
rem=a%b
Step 5: print the GCD value of b
Step 6: Stop the program

Program:
a=int(input("Enter the value of a :"))
b=int(input("Enter the value of b :"))
rem=(a%b)
while(rem!=0):
a=b
b=rem
rem=a%b
print("GCD of given two numbers is ",b)
Output:
Enter the value of a : 8
Enter the value of b : 6
GCD of given two numbers is 2

Result:
Thus the python program to find GCD of two numbers has been executed
successfully.

GE8161-PSPP LM Page 5 of 35
Ex.No:2
SQUARE ROOT OF A NUMBER (Newton’s Method)
Date:

Aim:
To write a python program to find Square root of a number using Newton’s Method.

Algorithm:
Step 1: Start the program
Step 2: Read the Number.
Step 3: Calculate approx=0.5*n
better=0.5*(approx+n/approx)
Step 4: while(better!=approx):
approx=better
better=0.5*(approx+n/approx)
return approx
Step 5: print Newton’s square root value.
Step 6: Stop the program

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)
print(netwonsqrt(10))
Output:

3.162277660168379

Result:
Thus the python program to find square root of a number using Newton’s method
has been executed successfully.

GE8161-PSPP LM Page 7 of 35
Ex.No:3 EXPONENTIATION OF A NUMBER
Date: (POWER OF A NUMBER)

Aim:
To write a python program to find the Exponentiation (power of a number)

Algorithm:
Step 1: Start the program
Step 2: Take the base and exponential value from the user.
Step 3: Initialize result value to 1
Step 4: using for loop to calculate result=result*a up to b+1
Step 5: Print the final result
Step 6: Stop the program

Program:
a=int(input("Enter the value of base a="))
b=int(input("Enter the value of exponential b="))
result=1
for i in range(1,b+1):
result=result*a
print("Power of a given base and exponent number = ",result)
Output:
Enter the value of base a =3
Enter the value of exponent b =2
Power of a given base and exponent number = 9

Result:
Thus the python program to find the Exponentiation of a number has been executed successfully.

GE8161-PSPP LM Page 9 of 35
Ex.No:4
FIND THE MAXIMUM OF A LIST OF NUMBERS
Date:

Aim:
To write a program to Find the maximum of a list of numbers.

Algorithm:
Step 1: Start the program
Step 2: Get the values in the list.
Step 3: Initialize max=list[0]
Step 4: Using a FOR loop to find maximum number
for a in list:
if(a>max):
max=a
Step 5: Print the value of maximum in the list
Step 6: Stop the program.

Program:
def number(list):
max=list[0]
for a in list:
if(a>max):
max=a
print("Maximum element in the list=",max)
list=[7,78,100,5,89,45]
number(list)
Output:
Maximum element in the list = 100

Result:
Thus the python program to find the maximum value in a list has been executed
successfully.

GE8161-PSPP LM Page 11 of 35
.Ex.No:5(A)
LINEAR SEARCH
Date:

Aim
To write a python program to perform linear search.

Algorithm:
Step 1: Start the program
Step 2: Define the list of elements
Step 3: Get the value to be searched
Step 4: Define a FOR loop to specify the range in which the value needs to be searched
Step 5: Using IF statement compare the search element with each element in the list
Step 6: If the condition returns a TRUE value, print that the element is found
Step 7: Stop the program

Program:
list=[8,12,15,5,2,6]
found=False
x=int(input("Enter the element to be searched : "))
for i in range(len(list)):
if(list[i]==x):
found=True
break
if(found==True):
print("Element is present in the list")
else:
print("Element is not present")
Output:
Output 1:
Enter the element to be searched : 2
Element is present in the list

Output 2:
Enter the element to be searched : 10
Element is not present

Result:
Thus the python program to perform Linear search has been executed successfully.

GE8161-PSPP LM Page 13 of 35
Ex.No:5(b)
BINARY SEARCH
Date:

Aim:
To write a python program to implement Binary Search
Algorithm:
Step 1: Start the program
Step 2: Compare x with the middle element.
Step 3: If x matches with middle element, we return the mid index.
Step 4: Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.
Step 5: Else (x is smaller) recur for the left half.
Step 6: Stop the program
Program:
def binary_search(list,item):
first=0
last=len(list)-1
found=False
while(first<=last and not found):
mid=(first+last)//2
if(list[mid]==item):
found = True
else:
if(item<list[mid]):
last=mid-1
else:
first=mid+1
return found
n=int(input("Enter the element to be searched : "))
s=binary_search([1,2,3,4,5,8],n)
if(s==True):
print("Element is present in list")
else:
print("Element is not present in list")
Output:
Output 1:
Enter the element to be searched : 2
Element is present in the list

Output 2:
Enter the element to be searched : 10
Element is not present

Result:
Thus the python program to implement Binary search has been executed successfully.

GE8161-PSPP LM Page 15 of 35
Ex.No:6(a)
Date: SELECTION SORT

Aim:
To write a python program to sort given numbers using selection sort.

Algorithm:
Step 1 : Start the program
Step 2: Initialize list values
Step 3 : Search the minimum element in the list using for loop
Step 4 : Swap with value at location MIN
Step 5 : Increment MIN to point to next element
Step 6 : Repeat until list is sorted
Step 7: Stop the program

Program:
array = [1,45,10,35,100,13,147,500,80]
print("Before Sorting = ",array)
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("After Sorting = ",array)
Output:

Before Sorting = [1,45,10,35,100,13,147,500,80]


After Sorting = [1,10,13,35,45,80,100,147,500]

Result:
Thus the python program for sorting the numbers using selection sort has been executed
successfully.

GE8161-PSPP LM Page 17 of 35
Ex.No:6(b)
INSERTION SORT
Date:

Aim:
To write a program to sort given numbers using insertion sort.

Algorithm:
Step 1: Start the program
Step 2 : If it is the first element, it is already sorted. return 1;
Step 3 : Pick next element
Step 4 : Compare with all elements in the sorted sub-list
Step 5 : Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 6 :Insert the value
Step 7 : Repeat until list is sorted
Step 8: Stop the program.

Program:
def insertionSort(alist):
for i in range(1,len(alist)):
current = alist[i]
while i>0 and alist[i-1]>current:
alist[i] = alist[i-1]
i = i-1
alist[i] = current
return alist
list=[5,2,1,9,0,4,6]
print("Before Sorting = ",list)
s=insertionSort(list)
print("After Sorting = ",s)
Output:
Before Sorting = [5,2,1,9,0,4,6]
After Sorting = [0,1,2,4,5,6,9]

Result:
Thus the python program for sorting the numbers using insertion sort has been executed
successfully.

GE8161-PSPP LM Page 19 of 35
Ex.No:7
MERGE SORT
Date:

Aim:
To write a python program to implement Merge Sort
Algorithm:
Step 1: Start the program
Step 2: Define the list on which the merger sort needs to be performed.
Step 3: Initialize the left half and right half of the list
Step 4: Apply the divide operation and spilt the halves further
Step 5: Continue the operation until unit blocks remain
Step 6: Perform the final merge operation of each halves and print the final list
Step 7: Stop the program.
Program:
def merge(left,right):
result = []
i,j=0,0
while((i<len(left))and(j<len(right))):
if(left[i]<=right[j]):
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result=result+left[i:]
result=result+right[j:]
return result

def mergesort(lst):
if(len(lst)<=1):
return lst
else:
middle=len(lst)//2
left=mergesort(lst[:middle])
right=mergesort(lst[middle:])
return merge(left,right)
lst=[23,1,2,45,67,89,4]
print("Before Sorting = ",lst)
list=mergesort(lst)
print("After Sorting = ",list)
Output:
Before Sorting = [23,1,2,45,67,89,4]
After Sorting = [1,2,4,23,45,67,89]

Result:
Thus the python program to implement merge sort has been executed successfully.

GE8161-PSPP LM Page 21 of 35
Ex.No:8
FIRST N PRIME NUMBERS
Date:

Aim:
To write a python program to print first n prime numbers

Algorithm:

Step 1: Start the program


Step 2: Enter the upper range of values.
Step 3: Divide each value in the range using the range from 2 to num(highest value)
Step 4: If the value is divisible in the range then it is not a prime number.
Step 5: Display the list of elements not divisible by any value in the range as prime numbers
Step 6: Stop the program

Program:
initial=1
n=int(input("Enter the limit="))
print("Prime number betweeen",initial,"and",n,"are")
for num in range (initial,n+1):
if num>1:
for i in range(2,num):
if(num%i==0):
break
else:
print(num)
Output:
Enter the limit =10
Prime numbers between 1 and 10 are
2
3
5
7

Result:
Thus the python program, to print first n prime numbers has been executed successfully.

GE8161-PSPP LM Page 23 of 35
Ex.No:9
Date: MATRIX MULTIPLICATION

Aim:
To write a python program to perform Matrix Multiplication.
Algorithm:
Step 1: Start the program
Step 2: Initialize the two input matrices and the resultant matrix.
Step 3: Iterate through the rows of the first matrix using a FOR Loop
Step 4: Iterate through the columns of the second matrix using a FOR Loop
Step 5: Store the multiplied value to each row of the result matrix.
Step 6: Print the final resultant matrix.
Step 7: Stop the program

Program:

X = [[12,7,3],[4 ,5,6],[7 ,8,9]]


Y = [[5,8,1,2],[6,7,3,0],[4,5,9,1]]
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)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Result:
Thus the python program to perform Matrix multiplication has been executed successfully.

GE8161-PSPP LM Page 25 of 35
Ex.No:10
Date: COMMAND LINE ARGUMENTS ( WORD COUNT )

Aim:
To write a python program that takes command line arguments for word count.
Algorithm:
Step 1: Start the program
Step 2: Get the file name as an argument from the user.
Step 3: Read each line from the file and split the line to form a list of words
Step 4: Find the length of items in the list and print it.
Step 5: Stop the program
Program:

import sys
words=0
with open(sys.argv[1],'r') as f:
for line in f:
text = line.split()
words = words + len(text)
print("Number of words : ", words)
f.close()
Input:
test.txt

Output:
Number of words : 49

Result:
Thus the python program that takes command line arguments for word count has been
executed successfully.

GE8161-PSPP LM Page 27 of 35
Ex.No:11
Date: FREQUENT WORDS IN A TEXT READ FROM A FILE

Aim:
To write a python program to find frequent words in a text read from a file.
Algorithm:
Step 1: Start the program
Step 2: Get the file name from the user.
Step 3: Import Counter class from collections module.
Step 4: Split the string into list using split( ), it will return the lists of words.
Step 5: Now pass the list to the instance of Counter class
Step 6: The function 'most_common( )' inside Counter will return the list of most frequent words
from list and its count.
Step 7: Stop the program
Program:

fname = input("Enter file name: ")


counts = dict()
from collections import Counter
with open(fname, 'r') as f:
for line in f:
words = line.split()
Counter = Counter(words)
most_occur = Counter.most_common(3)
print(most_occur)
Input:
input.txt

Output:
Enter file name: input.txt
[('a', 6), ('Python', 5), ('is', 4)]

Result:
Thus the python program to find frequent words in a text read from a file has been executed
successfully.

GE8161-PSPP LM Page 29 of 35
Ex.No:12
Date: SIMULATION OF ELLIPTICAL ORBIT USING PYGAME

Aim:
To write a python program for simulating elliptical orbit using Pygame.
Algorithm:
Step 1: Start the program
Step 2: Import the Required packages.
Step 3: Define the screen space to display the Elliptical orbit in that space.
Step 4: Using pygame.event.get() run the orbit till event get closed.
Step 5: For each degree,find the coordinates for the orbit to rotate and display in the screen with
elliptical curve.
Step 6:Stop the program
Program:
import pygame
import math
import sys
pygame.init()
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption("ELLIPTICAL ORBITS")
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))
#pygame.draw.circle(screen, (color of circle), [x, y coordinates], radius of circle)
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, 255, 0), [x1, y1], 15)
pygame.display.flip()
clock.tick(25) #We can modify the speed by changing the clock tick
Output:

Result:
Thus the python program for simulating elliptical orbit using Pygame has been executed
successfully.

GE8161-PSPP LM Page 31 of 35
Ex.No:13
Date: SIMULATION OF BOUNCING BALL USING PYGAME

Aim:
To write a python program for simulating bouncing ball using Pygame.
Algorithm:
Step 1: Start the program
Step 2: Import the Required packages.
Step 3: Define the required variables.
Step 4: Define the screen space to display the bouncing ball in that space.
Step 5: Using pygame.event.get() bounce the ball.
Step 6:Stop the program
Program:
import sys, pygame
pygame.init()
size = width, height = 1000, 700
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("BOUNCING BALL")
ball = pygame.image.load("ball.bmp")
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(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Output:

Result:
Thus the python program for simulating bouncing ball using Pygame has been executed
successfully.

GE8161-PSPP LM Page 33 of 35

You might also like