A
Practical File
On
Python Programming Lab
(LC-CSE-215G)
Submitted
For
Bachelor of Technology
In
Computer Science & Engineering
At
Chaudhary Ranbir Singh State Institute of Engineering and
Technology, SilaniKeso, Jhajjar (124103)
Submitted to: Submitted By:
Ms. Manisha phogat Name- Nitesh Kumar
Assistant Professor Roll no- 231901246
(CSE dept.) Branch-CSE
Sem-3 rd
INDEX
Sr. Practical Date Page no. Teacher
No. sign.
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
Program 9
Write a program to add two matrices taking input from user:-
Program:
rows = int(input('Enter number of rows: '))
cols = int(input('Enter number of column:
')) print()
print('Enter values for matrix A')
matrix_A = [[int(input(f"column {j+1} -> ENter {i+1} element:")) for j in
range(cols)] for i in range(rows) ]
print()
print('Enter values for matrix B ')
matrix_B = [[int(input(f"column {j+1} -> ENter {i+1} element:")) for j in
range(cols)] for i in range(rows) ]
print()
print('Matrix-A
:') for i in
matrix_A:
print(i)
print()
print('Matrix-B
:') for i in
matrix_B:
print(i)
result = [[0 for j in range(cols)] for i in range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = matrix_A[i][j] + matrix_B[i][j]
print()
print('Addition of Matrix-A and Matrix-B is :')
for i in result:
print(i)
Output:
Program 1
Compute the GCD of two numbers.
Program:
def gcd(a,b):
if a>0 and
b>0: if
a>b:
c=a
a=
b=
c
if(b%a==
0):
return a
return
gcd(b%a,a) elif
a==0 or b==0:
return 0
else:
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
print("GCD = ",gcd(a,b))
➢ Output :-
Program 2
Find the square root of number (Newton’s Method)
Program:
def sqrt(numb,tolerance):
x=numb
while(True):
root= 0.5 * (x+(numb/x))
if abs(root-x)<=tolerance:
break
x=root
return root
a=int(input("Enter the number:"))
b=float(input("Enter the tolerance:"))
print("Square root = ",sqrt(a,b))
• Output:
Program 3
Exponentiation (power of a number)
Program:
a=int(input("Enter the number: "))
b=int(input("Enter power: "))
print("Exponentiation of ",a," = ",a**b)
Output:
Program 4
Find the maximum of a list of numbers.
Program:
n=int(input("Enter how many Numbers you want to input\n"))
l1=[]
i=0
while i<n:
[Link](int(input("Enter the number\n")))
i+=1
print("List: ",l1)
i=1
max=l1[0]
while i<n:
if max<l1[i]:
max=l1[i]
i+=1
print("Maximum number of the list = ",max)
Output:
Program 8
Write a program in Python to print first n prime numbers.
Program:
def is_prime(numb):
for i in range(2,numb):
if(numb%i==0):
return False
return True
def print_prime(num):
count=0
for e in range(2,10000):
flag=is_prime(e)
if(flag==True):
count+=1
if(count <= num):
print(e,end=' ')
else:
break
n=int(input("Enter the value of N\n"))
print("Prime number:")
print_prime(n)
Output:
Program 11
Write a Python program to find the most frequent words in a text read from
a file.
Program:
from collections import Counter
import string
def get_most_frequent_word(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
# Read the file and remove punctuation
text = [Link]().translate([Link]('', '', [Link]))
# Convert to lowercase and split into words
words = [Link]().split()
# Use Counter to count the occurrences of each word
word_counts = Counter(words)
# Get the most common word
most_common_word, count = word_counts.most_common(1)[0]
return most_common_word, count
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
if name == " main ":
file_path = input("Enter the path to the text file: ")
result = get_most_frequent_word(file_path)
if result:
word, count = result
print(f"\nMost frequent word: '{word}' (Count: {count})")
Output:
Program 12
Simulate elliptical orbits in Pygame.
Program:
import pygame
import sys
import math
# Initialize Pygame
[Link]()
# Constants
width, height = 800, 600
center_x, center_y = width // 2, height // 2
ellipse_width, ellipse_height = 400, 200
angular_speed = 0.02 # Adjust this for different speeds
# Colors
white = (128, 128, 142)
black = (0, 0, 0)
# Create Pygame window
screen = [Link].set_mode((width, height))
[Link].set_caption("Elliptical Orbits")
clock = [Link]()
# Main loop
angle = 0
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()
[Link]()
# Clear the screen
[Link](white)
# Calculate position in the ellipse
x = center_x + ellipse_width * 0.5 * [Link](angle)
y = center_y + ellipse_height * 0.5 * [Link](angle)
# Draw ellipse
[Link](screen, black, (center_x - ellipse_width // 2, center_y - ellipse_height
// 2, ellipse_width, ellipse_height), 1)
# Draw the orbiting object
[Link](screen, black, (int(x), int(y)), 10)
# Update angle for the next frame
angle += angular_speed
# Update the display
[Link]()
# Control the frame rate
[Link](60)
Output:
Program 13
Simulate bouncing ball using Pygame.
Program:
import pygame
import sys
# Initialize Pygame
[Link]()
# Constants
width, height = 800, 600
ball_radius = 20
ball_color = (0, 0, 0)
ball_speed = 5
# Create Pygame window
screen = [Link].set_mode((width, height))
[Link].set_caption("Bouncing Ball")
clock = [Link]()
# Initial ball position and velocity
ball_x, ball_y = width // 2, height // 2
ball_velocity_x, ball_velocity_y = ball_speed, ball_speed
# Main loop
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()
[Link]()
# Update ball position
ball_x += ball_velocity_x
ball_y += ball_velocity_y
# Bounce off the walls
if ball_x - ball_radius < 0 or ball_x + ball_radius > width:
ball_velocity_x = -ball_velocity_x
if ball_y - ball_radius < 0 or ball_y + ball_radius > height:
ball_velocity_y = -ball_velocity_y
# Clear the screen
[Link]((128, 128, 142))
# Draw the ball
[Link](screen, ball_color, (int(ball_x), int(ball_y)), ball_radius)
# Update the display
[Link]()
# Control the frame rate
[Link](60)
Output:
Program 5
Linear search and Binary search
Linear Search:
Program:
def linear_search(array,x):
for i in range(0,len(array)):
if array[i]==x:
return i
return -1
l1=eval(input("Input the List:\n"))
print("List: ",l1)
numb=int(input("Enter the number to find:\n"))
index=linear_search(l1,numb)
if(index>=0):
print(numb,"is found at index ",index)
else:
print("Number not found in the list")
Output:
Binary Search:
Program:
def binary_search(array,low,high,x):
if low==high:
if array[low]==x:
return low
else:
return -1
else:
mid=(low+high+1)//2
if array[mid]==x:
return mid
elif array[mid]>x:
return binary_search(array,low,mid-1,x)
else:
return binary_search(array,mid+1,high,x)
n=int(input("Enter how many Numbers you want to input\n"))
l1=[]
i=0
while i<n:
[Link](int(input("Enter the number\n")))
i+=1
[Link]()
print("List: ",l1)
numb=int(input("Enter the element to find:\n"))
index=binary_search(l1,0,n-1,numb)
if(index>=0):
print(numb,"is found at index ",index)
else:
print("Number not found in the list")
Output:
Program 6
Selection Sort and Insertion Sort.
Selection Sort:
Program:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
l1=[23,10,5,7,87,98,35]
print("List before sort: ",l1)
selection_sort(l1)
print("List after sort: ",l1)
Output:
Insertion Sort:
Program:
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print("Name - Varun\nRoll no.-221901258")
n=int(input("Enter how many Numbers you want to input\n"))
l1=[]
i=0
while i<n:
[Link](int(input("Enter the number\n")))
i+=1
print("List before sort: ",l1)
insertion_sort(l1)
print("List after sort: ",l1)
Output:
Program 7
Write a program in python to implement merge sort.
Merge Sort
Program:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Find the middle of the array
left_half = arr[:mid] # Split the array into two halves
right_half = arr[mid:]
# Recursive calls to sort the two halves
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
# Merge the two halves back together
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
# Check if any elements were left in the left_half
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
# Check if any elements were left in the right_half
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
l1=[23,10,5,7,87]
print("List before sort: ",l1)
merge_sort(l1)
print("List after sort: ",l1)
Output:
Program 10
Programs that take command line arguments (word count)
Program:
import sys
def word_count(filename):
try:
with open(filename, 'r') as file:
text = [Link]()
words = [Link]()
print(f"The file '{filename}' contains {len(words)} words.")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
if __name__ == "__main__":
if len([Link]) != 2:
print("Usage: python word_count.py <filename>")
else:
word_count([Link][1])
Output: