You are on page 1of 19

PRACTICAL FILE

PYTHON (KCS-453)
B.TECH (CSE) -4th SEMESTER
BATCH (2021-2025)

KCC INSTITUTE OF TECHNOLOGY AND MANAGEMENT , Greater Noida


Dr. A.P.J Abdul Kalam Technical University

SUBMITTED BY: SUBMITTED TO:


Name:- NITIN KUMAR Ms Ankita Agarwal
Roll no:-210492153033
INDEX
Page
S. No. Documents
No.

1 To write a python program that takes in command line arguments as 1


input and print the number of arguments.
2 To write a python program to perform Matrix Multiplication. 2

3 To write a python program to compute the GCD of two numbers 3

4 To write a python program to find the most frequent words in a text 4


file.
To write a python program find the square root of a number
5 5
(Newton’s method).

6 6
To write a python program exponentiation (power of a number).

7 7
To write a python program find the maximum of a list of numbers.

8 8
To write a python program linear search.

9 To write a python program Binary search. 9

10 To write a python program selection sort. 10

To write a python program Insertion sort.


11 11

12 To write a python program merge sort. 12

13 To write a python program first n prime numbers. 14

14 To write a python program simulate bouncing ball in Pygame. 15


EXPERIMENT:-03
Aim:
To compute the greatest common divisor (GCD) of two numbers.
Algorithm:
1. Start the Program.
2. Take two numbers from the user.
3. Pass the two numbers as arguments to a recursive function.
4. When the second number becomes 0, return the first number.
5. Else recursively call the function with the arguments as the second number and the remainder when
the first number is divided by the second number.
6. Return the first number which is the GCD of the two numbers.
7. Print the GCD.
8. Stop the Program.
Program:
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print "GCD of",a,"and",b,"is:",GCD
Sample Output:

Result:
Thus the python program to compute the GCD of two numbers was executed successfully.
EXPERIMENT:-05
Aim:
To find the square root of a number using Newton’s method.
Algorithm:
1. Start the Program.
2. First parameter is the value whose square root will be obtained.
3. Calculate the better result.
4. Stop the Program.
Program:
print("This program will determine a square root using Newton's Method.")
n=int(input("Enter the Value of n:"))
guess = n / 2.0
while True:
accuracy = (guess + n / guess) / 2.0
if abs(guess-accuracy) < 0.00001:
print(accuracy)
break
guess = accuracy
Sample Output:

Result:
Thus the python program to find the square root of a nmber using newton’s method has been executed
successfully.
EXPERIMENT:-06
Aim:
To find the exponentiation (Power of a Number).
Algorithm:
1. Start the Program.
2. Take the base and exponential value from the user.
3. Pass the number as argument to a recursive function to find the power of a number.
4. If the exponential power is equal to 1, return the base value.
5. If the exponential power is not equal to 1, return the base value multiplied with the power function.
6. Print the result.
7. Stop the Program.
Program:
def pow(x,y):
if y==0:
return 1
res=pow(x,y//2)
if y%2==0:
return res*res
else:
return x*res*res
x=int(input("Enter the Value of x:"))
y=int(input("Enter the Value of y:"))
print "The Power of",x,y,"is: ",pow(x,y)
Sample Output:

Result:
Thus the python program to find the exponentiation for the given number has been executed
successfully.
EXPERIMENT:-07
Aim:
To find the maximum number from the given list of numbers.
Algorithm:
1. Get the number of elements as input and store it in a variable.
2. Take the elements from the one by one.
3. Sort the list of elements in ascending order.
4. Print the last element from the list.
5. Stop the Program.
Program:
size=int(input("Enter the number of Elements:"))
list=[]
flag=False
print("Enter the Elements")
for i in range(0, size):
list.append(int(input()))
print "The Elements in the list are:",list
max=list[0]
for i in range(0, size):
if list[i]>max:
max=list[i]
print "The Maximum Element is:",max
Sample Output:

Result:
Thus the python program for finding the maximum number from the list has been executed
successfully.
EXPERIMENT:-08
Aim:
To search the element from the given list using linear search.
Algorithm:
1. Start the Program.
2. Set the value of i to 1
3. If i>n, print element not found.
4. If list[i] = ele, print element is found at index i.
5. Set i to i+1
6. Stop the Program.
Program:
size=int(input("Enter the number of Elements:"))
list=[]
flag=False
print("Enter the Elements")
for i in range(0, size):
list.append(int(input()))
print "The Elements in the list are:",list
ele=int(input("Enter the Element to be Searched:"))
for i in range(0, size):
if ele==list[i]:
flag=True
break
if flag==True:
print("The Element {0} was found at position {1}".format(ele,i+1))
elif flag==False:
print("The Element {} is not found in the List".format(ele))
Sample Output:

Result:
Thus the python program to search an element from the list using linear search has been executed successfully.
EXPERIMENT:-09
Aim:
To search an element from the given list using binary search.
Algorithm:
1. Start the Program.
2. Set the value of i to 1
3. If i>n, print element was not found.
4. If num_list[midpoint] = ele, print element is found at index i.
5. Set i to i+1
6. Stop the Program.
Program:
n=int(input("Enter the Number of Elements:"))
num_list=[]
print("Enter the Elements")
for i in range(0,n):
num_list.append(int(input()))
print(num_list)
ele=int(input("Enter the Element to be Searched:"))
low=0
high=n-1
mid=(low+high)//2
while low<=high:
if num_list[mid]==ele:
print "Element:",ele, "is found at position",mid+1
break
elifnum_list[mid]<ele:
low=mid+1
else:
high=mid-1
mid=(low+high)//2
if low>high:
print "Element:",ele," was not found!"
Sample Output:

Result: Thus the python program to search an element from the list using linear search has been executed successfully.
EXPERIMENT:-10
Aim:
To sort the list of elements in ascending order using selection sort.
Algorithm:
1. Start the Program.
2. Set MIN to location 0.
3. Search the minimum element in the list.
4. Swap with value at location MIN.
5. Increment MIN to point to next element.
6. Repeat the steps until the list is sorted.
7. Stop the Program.
Program:
size=int(input("Enter the number of Elements:"))
list=[]
print("Enter the Elements")
for i in range(0, size):
list.append(int(input()))
print "The Elements in the list are:",list
for i in range(0, size-1):
min=i
for j in range(i+1,size):
if list[j]<list[i]:
min=j
temp=list[i]
list[i]=list[min]
list[min]=temp
print(list)
Sample Output:

Result:
Thus the python program to sort the given elements using selection sort has been executed successfully.
EXPERIMENT:-11
Aim:
To sort the list of elements in ascending order using insertion sort.
Algorithm:
1. Start the Program.
2. If it is the first element, it is already sorted. Return 1.
3. Select the next element and compare with remaining all the elements in the list.
4. Shift all the elements in the list that is greater than the value to be sorted.
5. Insert the value.
6. Repeat the steps until the list is sorted.
7. Stop the Program.
Program:
n=int(input("Enter the number of Elements:"))
input_list=[]
print("Enter the Elements:")
for i in range(0, n):
input_list.append(int(input()))
print "The Elements in the list are:",input_list
for i in range(1, len(input_list)):
j=i
while j>0 and input_list[j-1]>input_list[j]:
temp=input_list[j]
input_list[j]=input_list[j-1]
input_list[j-1]=temp
j-=1
print "The Sorted List are:",input_list
Sample Output:

Result: Thus the python program to sort the given elements using insertion sort has been executed successfully.
EXPERIMENT:-12
Aim:
To sort the list of elements in ascending order using merge sort.
Algorithm:
1. Start the Program.
2. Divide the list of elements in the list into 2.
3. Then divide each group into n subgroups.
4. Sort the elements in each group in ascending order.
5. Merge all the elements in each group into single list.
6. Stop the Program.
Program:
def merge_sort(list):
if len(list)>1:
mid=len(list)//2
left=list[:mid]
right=list[mid:]
merge_sort(left)
merge_sort(right)
i=0
j=0
k=0
while i<len(left)and j<len(right):
if left[i]<right[j]:
list[k]=left[i]
i=i+1
else:
list[k]=right[j]
j=j+1
k=k+1
while i<len(left):
list[k]=left[i]
i=i+1
k=k+1
while j<len(right):
list[k]=right[j]
j=j+1
k=k+1
size=int(input("Enter the Number of Elements:"))
list=[]
print("Enter the Elements:")
for i in range(0,size):
list.append(int(input()))
print "The Unsorted Elements are:",list
merge_sort(list)
print "The Sorted Elements are:",list

Sample Output:

Result:
Thus the python program to sort the given elements using merge sort has been executed successfully.
EXPERIMENT:-13
Aim:
To find the prime numbers for the first n values.
Algorithm:
1. Start the Program.
2. Get the number to be checked and store it in a variable.
3. Initialize the count variable to 0.
4. Let the for loop range from 2 to half of the number.
5. Then find the number of divisors using 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 result.
8. Stop the Program.
Program:
# To find first 'N' prime numbers
i=1
x = int(input("Enter the number:"))
for k in range (1, (x+1), 1):
c=0;
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
else:
k=k-1
i=i+1
Output:

Result:
Thus the python program to find first n prime numbers has been executed successfully .
EXPERIMENT:-02
Aim:
To multiply two matrices.
Algorithm:
1. Start the program.
2. Declare and initialize necessary variables.
3. Enter the elements of matrix row wise using loop.
4. Check the rows and columns of two marices.
5. If number of rows and columns of 2 matrix are equal, multiply the matrices using nested loops.
6. Print the product of two matrix.
7. Stop the Program.
Program:
# Python Program - Matrix Multiplication
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = [[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]]
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)
Sample Output:

Result: Thus the python program to multiply two matrices has been executed successfully.
EXPERIMENT:-01
Aim:
To take input from the command line and find the arguments.
Algorithm:
1. Start the Program.
2. Get the command line from the user.
3. Read the command line included and return arguments.
4. Stop the Program.
Program:
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)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
print ("Second argument: %s" % str(sys.argv[2]))

Sample Output:

Result:
Thus the python program to take input from command line arguments has been executed.
EXPERIMENT:-04
Aim:
To find the most frequent words in a text read from a file.
Algorithm:
1. Start the Program.
2. Get the input from the user.
3. Read each line from the file to form a list of words.
4. Use for loop to traverse through the words in the list.
5. Find the number of times the words occurred.
6. Print the Result.
7. Stop the Program.
Program:
import re
import string
frequency = {}
document_text = open('test.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]
test.txt
Based on the information received from the Principal of the College where your are presently working, I wish
to inform that you are appointed as External Examiner to conduct the Practical.
Sample Output:

Result:
Thus the python program to read the most frequent words in a text from a file has been executed successfully.
Pygame Programs
Pygame Installation
Step 1: Download Python 2.7.x or Python 3.6.x from https://www.python.org/download/releases/2.7.
Step 2: Install the .exe file in any drive (location).
Step 3: Finally click finish button to complete the installation.
Step 4: Choose a version of pygame compatible with your python version installed.
Step 5: Goto https://www.pygame.org/download.html
Step 6: Choose pygame-1.9.2a0.win32-py2.7.msi and download it.
Step 7: Install the downloaded pygame file which will be installed in python directory.
Step 8: Finally click finish button to complete the installation.
Step 9: To test pygame is installed correctly or not – Open Python IDLE Editor
Step 10: Type import pygame and print the version.
Step 11: If the version appears properly, then pygame has been successfully installed.
Step 12: If any error (ImportError) occurs, then try to install pygame again by checking proper version
of python and compatibility with pygame.
EXPERIMENT:-14
Aim:
To simulate bouncing ball in python using pygame.
Algorithm:
1. Start the Program.
2. Import necessary packages for pygame.
3. Set the value for drawing the circle.
4. Add the pygame window with necessay features.
5. Display the simulation of bouncing ball.
6. Stop the Program.
Program:
import pygame, sys, time, random
from pygame.locals import *
from time import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption(“Ball 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
yy= sh
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
sleep(.006)
y+= 1
if y>sh:
pygame.draw.circle(windowSurface, GREEN , (250,yy), 13, 0)
sleep(.0001)
yy +=-1
if yy<-.00001:
y=0
y+= 1
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()

sys.exit()
Sample Output:

Result:
Thus the python program to simulate bouncing ball using pygame has been executed successfully.

You might also like