Gyan Ganga Institute of Technology and Sciences,
Jabalpur
AIML
Python Lab (CS -506)
Practical File
NAME:
ENROLLMENTNUMBER:
BRANCH: CSE-3
SESSION: July-December (2024-25)
Submitted to
Prof. Vikash Verma
Dept. of Computer Science and Engineering
Index
S.No. Experiments Date Sign
1 To write a Python program to find GCD of two
numbers.
2 To write a Python Program to find the square root of a
number by Newton’s Method.
3 To write a Python program to find the exponentiation
of a number.
4 To write a Python Program to find the maximum from
a list of numbers.
5 To write a Python Program to perform Linear Search
6 To write a Python Program to perform binary search.
7 To write a Python Program to perform selection sort.
8 To write a Python Program to perform insertion sort.
9 To write a Python Program to perform Merge sort.
10 To write a Python program to find first n prime
numbers.
11 To write a Python program to multiply matrices.
12 To write a Python program for command line
arguments.
13 To write a Python program to find the most frequent
words in a text read from a file.
14 To write a Python program to simulate elliptical orbits
in Pygame.
15 To write a Python program to bouncing ball in
Pygame.
Program 1 : To write a Python program to find GCD of two numbers
Algorithm:
1. Input: Read two integers a and b.
2. Check Base Case: If b == 0, the GCD is a. Terminate.
3. Recursive Step: Otherwise, compute GCD(b, a % b).
4. Output: Return the computed GCD.
Program:
def find_gcd(a, b):
"""
Function to compute GCD of two numbers using Euclid's Algorithm.
""" while b != 0:
a, b = b, a % b
return a
# Input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Finding GCD
gcd = find_gcd(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} is {gcd}.")
Enter the first number: 48
Enter the second number: 18
The GCD of 48 and 18 is 6.
Program2: To write a Python Program to find the square root of a number by Newton’s
Method.
Program:
def newton_sqrt(n, tolerance=1e-6):
"""
Function to compute the square root of a number using Newton's Method.
"""
if n < 0:
raise ValueError("Cannot compute the square root of a negative number.")
# Initial guess
x = n / 2 if n != 0 else 0
while True:
# Update the guess
next_x = 0.5 * (x + n / x)
# Check for convergence
if abs(next_x - x) < tolerance:
break
x = next_x
return next_x
# Input from the user
number = float(input("Enter the number: "))
# Finding square root
try:
sqrt_value = newton_sqrt(number)
print(f"The square root of {number} is approximately {sqrt_value:.6f}.")
except ValueError as e:
print(e)
Enter the number: 25
The square root of 25.0 is approximately 5.000000.
Program 3: To write a Python program to find the exponentiation of a number
Program:
def exponentiation(base, exponent):
"""
Function to compute the exponentiation of a number.
"""
result = 1
if exponent >= 0:
for _ in range(exponent):
result *= base
else:
for _ in range(-exponent):
result *= base
result = 1 / result
return result
# Input from the user
base = float(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
# Calculating exponentiation
result = exponentiation(base, exponent)
# Displaying the result
print(f"The result of {base}^{exponent} is {result:.6f}.")
Program 4: To write a Python Program to find the maximum from a list of numbers.
Program:
def find_maximum(numbers):
"""
Function to find the maximum number in a list.
"""
if not numbers: # Check for empty list
raise ValueError("The list is empty.")
# Initialize the first element as maximum
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
# Input from the user
try:
numbers = list(map(float, input("Enter numbers separated by spaces: ").split()))
max_value = find_maximum(numbers)
print(f"The maximum value in the list is: {max_value}")
except ValueError as e:
print(e)
Enter numbers separated by spaces: 10 45 2 89 34
The maximum value in the list is: 89.0
Program5: To write a Python Program to perform Linear Search
Algorithm for Linear Search
1. Input: Read the list of numbers and the target value to be searched.
2. Iterate: Go through each element of the list:
o If the current element matches the target, return its position.
3. Output: If the target is not found, return a message indicating it is not in the list.
Program:
def linear_search(numbers, target):
"""
Function to perform a linear search in a list.
"""
for index, num in enumerate(numbers):
if num == target:
return index # Return the index of the target
return -1 # Return -1 if the target is not found
# Input from the user
try:
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
target = int(input("Enter the target number to search: "))
# Perform linear search
result = linear_search(numbers, target)
if result != -1:
print(f"The target {target} is found at index {result}.")
else:
print(f"The target {target} is not in the list.")
except ValueError:
print("Invalid input. Please enter integers only.")
Enter numbers separated by spaces: 10 20 30 40 50
Enter the target number to search: 30
The target 30 is found at index 2.
Program 6: To write a Python Program to perform binary search.
Program:
def binary_search(numbers, target):
"""
Function to perform binary search in a sorted list.
"""
low, high = 0, len(numbers) - 1
while low <= high:
mid = (low + high) // 2
if numbers[mid] == target:
return mid # Target found
elif numbers[mid] < target:
low = mid + 1 # Search in the right half
else:
high = mid - 1 # Search in the left half
return -1 # Target not found
# Input from the user
try:
numbers = list(map(int, input("Enter sorted numbers separated by spaces: ").split()))
target = int(input("Enter the target number to search: "))
# Perform binary search
result = binary_search(numbers, target)
if result != -1:
print(f"The target {target} is found at index {result}.")
else:
print(f"The target {target} is not in the list.")
except ValueError:
print("Invalid input. Please enter integers only.")
Enter sorted numbers separated by spaces: 10 20 30 40 50
Enter the target number to search: 30
The target 30 is found at index 2.
Program 7: To write a Python Program to perform selection sort.
Algorithm for Selection Sort
Selection Sort is a simple comparison-based sorting algorithm that works as follows:
1. Input: Read a list of numbers.
2. Outer Loop: Iterate through the list, assuming the current position as the minimum
index.
3. Inner Loop:
o Compare the current element with the rest of the list to find the smallest element.
o Swap the smallest element with the current position.
4. Repeat: Continue until the entire list is sorted.
5. Output: Return the sorted list.
Program:
def selection_sort(numbers):
"""
Function to sort a list of numbers using Selection Sort.
"""
n = len(numbers)
for i in range(n):
# Assume the current index is the minimum
min_index = i
for j in range(i + 1, n):
if numbers[j] < numbers[min_index]:
min_index = j
# Swap the minimum element with the current element
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
return numbers
# Input from the user
try:
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Perform selection sort
sorted_numbers = selection_sort(numbers)
# Display the sorted list
print(f"The sorted list is: {sorted_numbers}")
except ValueError:
print("Invalid input. Please enter integers only.")
Enter numbers separated by spaces: 64 34 25 12 22 11 90
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
Program 8: To write a Python Program to perform insertion sort.
Algorithm for Insertion Sort
Insertion Sort builds the sorted list one element at a time by inserting each element into its
correct position:
1. Input: Read a list of numbers.
2. Outer Loop: Start from the second element and iterate through the list.
3. Inner Loop:
o Compare the current element with the sorted portion of the list (elements before
it).
o Shift larger elements one position to the right to make space.
o Insert the current element into its correct position.
4. Output: Return the sorted list.
Program:
def insertion_sort(numbers):
"""
Function to sort a list of numbers using Insertion Sort.
"""
n = len(numbers)
for i in range(1, n):
# Current element to be inserted
key = numbers[i]
j=i-1
# Shift elements of the sorted portion to the right
while j >= 0 and numbers[j] > key:
numbers[j + 1] = numbers[j]
j -= 1
# Insert the current element at its correct position
numbers[j + 1] = key
return numbers
# Input from the user
try:
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Perform insertion sort
sorted_numbers = insertion_sort(numbers)
# Display the sorted list
print(f"The sorted list is: {sorted_numbers}")
except ValueError:
print("Invalid input. Please enter integers only.")
Enter numbers separated by spaces: 64 34 25 12 22 11 90
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
Program 9: To write a Python Program to perform Merge sort
Algorithm for Merge Sort
1. Divide: Split the list into two halves until each sublist contains one element.
2. Conquer:
o Recursively sort each half.
3. Combine:
o Merge two sorted sublists into a single sorted list.
Program:
Merge Sort is a divide-and-conquer sort def merge_sort(numbers):
"""
Function to sort a list of numbers using Merge Sort.
"""
if len(numbers) > 1:
# Divide the list into two halves
mid = len(numbers) // 2
left_half = numbers[:mid]
right_half = numbers[mid:]
# Recursively sort both halves
merge_sort(left_half)
merge_sort(right_half)
# Merge the sorted halves
i=j=k=0
# Copy data to the original list while sorting
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
numbers[k] = left_half[i]
i += 1
else:
numbers[k] = right_half[j]
j += 1
k += 1
# Check for remaining elements in the left half
while i < len(left_half):
numbers[k] = left_half[i]
i += 1
k += 1
# Check for remaining elements in the right half
while j < len(right_half):
numbers[k] = right_half[j]
j += 1
k += 1
return numbers
# Input from the user
try:
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Perform merge sort
sorted_numbers = merge_sort(numbers)
# Display the sorted list
print(f"The sorted list is: {sorted_numbers}")
except ValueError:
print("Invalid input. Please enter integers only.")
Enter numbers separated by spaces: 64 34 25 12 22 11 90
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
Program 10: To write a Python program to find first n prime numbers
Algorithm to Find the First n Prime Numbers
1. Input: Read the value n, which represents how many prime numbers to find.
2. Iterate: Start checking numbers from 2 upwards.
3. Check for Prime: For each number, check if it is prime by trying to divide it by all
numbers less than it (up to its square root).
4. Store Prime Numbers: If a number is prime, add it to a list.
5. Stop when n primes are found.
Program:
import math
def is_prime(num):
"""
Function to check if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def first_n_primes(n):
"""
Function to find the first n prime numbers.
"""
primes = []
num = 2 # Start checking from number 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
# Input from the user
try:
n = int(input("Enter the number of primes to find: "))
# Find the first n primes
primes = first_n_primes(n)
# Display the result
print(f"The first {n} prime numbers are: {primes}")
except ValueError:
print("Please enter a valid integer.")
Enter the number of primes to find: 10
The first 10 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Program 11: To write a Python program to multiply matrices
Algorithm to Multiply Matrices
1. Input: Read two matrices AAA and BBB of compatible sizes (i.e., the number of
columns in matrix AAA should equal the number of rows in matrix BBB).
2. Check Compatibility: Ensure that matrix multiplication is possible (columns of AAA
must be equal to rows of BBB).
3. Multiply: Use nested loops to compute the dot product of rows of AAA with columns of
BBB.
4. Store: Store the result in a new matrix.
5. Output: Return the resulting matrix.
Program:
def multiply_matrices(A, B):
"""
Function to multiply two matrices A and B.
"""
# Check if multiplication is possible
if len(A[0]) != len(B):
raise ValueError("Number of columns in A must be equal to number of rows in B.")
# Initialize the result matrix with zeros
result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
# Perform matrix multiplication
for i in range(len(A)): # Iterate over rows of A
for j in range(len(B[0])): # Iterate over columns of B
for k in range(len(B)): # Iterate over rows of B
result[i][j] += A[i][k] * B[k][j]
return result
# Input matrices
try:
# Matrix A
rows_A = int(input("Enter the number of rows in matrix A: "))
cols_A = int(input("Enter the number of columns in matrix A: "))
A = []
print("Enter the elements of matrix A:")
for i in range(rows_A):
row = list(map(int, input().split()))
A.append(row)
# Matrix B
rows_B = int(input("Enter the number of rows in matrix B: "))
cols_B = int(input("Enter the number of columns in matrix B: "))
if cols_A != rows_B:
print("Matrix multiplication is not possible. Columns of A must equal rows of B.")
else:
B = []
print("Enter the elements of matrix B:")
for i in range(rows_B):
row = list(map(int, input().split()))
B.append(row)
# Multiply matrices
result = multiply_matrices(A, B)
# Display the result
print("The resulting matrix is:")
for row in result:
print(" ".join(map(str, row)))
except ValueError:
print("Invalid input. Please enter valid integers.")
Enter the number of rows in matrix A: 2
Enter the number of columns in matrix A: 3
Enter the elements of matrix A:
123
456
Enter the number of rows in matrix B: 3
Enter the number of columns in matrix B: 2
Enter the elements of matrix B:
78
9 10
11 12
The resulting matrix is:
58 64
139 154.
Program 12: To write a Python program for command line arguments.
Steps to Handle Command Line Arguments
1. Import the sys module: To access sys.argv.
2. Access Arguments: sys.argv will contain the command-line arguments passed to the
script.
3. Handle Arguments: Write logic to process the arguments passed from the command
line.
4. Run the script: The script can be run from the terminal, passing arguments along with
the script name.
Program:
import sys
def main():
# Check if enough arguments are passed
if len(sys.argv) < 2:
print("Usage: python script_name.py <arg1> <arg2> ...")
sys.exit(1)
print("Arguments passed to the script:")
# Display all arguments (sys.argv[0] is the script name)
for i, arg in enumerate(sys.argv):
print(f"Argument {i}: {arg}")
# Example: Add numbers passed as arguments
if len(sys.argv) > 2: # Assuming the arguments are numbers
try:
numbers = [int(arg) for arg in sys.argv[1:]]
total = sum(numbers)
print(f"The sum of the arguments is: {total}")
except ValueError:
print("Please provide valid integers as arguments.")
if __name__ == "__main__":
main()
python script_name.py 10 20 30
Arguments passed to the script:
Argument 0: script_name.py
Argument 1: 10
Argument 2: 20
Argument 3: 30
The sum of the arguments is: 60
Program 13: To write a Python program to find the most frequent words in a text read
from a file.
To find the most frequent words in a text file, we can follow these steps:
1. Read the file: Open the file in read mode and extract its content.
2. Process the Text: Convert all text to lowercase to avoid case sensitivity and remove
punctuation.
3. Count Word Frequencies: Use a dictionary or a Counter from the collections
module to count word frequencies.
4. Find the Most Frequent Words: Sort the words based on their frequency and display
the most frequent ones.
Program:
import string
from collections import Counter
def process_text(file_path):
"""
Function to read a file, clean the text, and find the most frequent words.
"""
try:
# Open the file and read the content
with open(file_path, 'r') as file:
text = file.read()
# Convert the text to lowercase and remove punctuation
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
# Split the text into words
words = text.split()
# Count the frequency of each word using Counter
word_count = Counter(words)
# Find the most common words
most_common = word_count.most_common()
return most_common
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
return []
def display_most_frequent_words(file_path, top_n=10):
"""
Function to display the most frequent words in the file.
"""
most_common = process_text(file_path)
if most_common:
print(f"The {top_n} most frequent words are:")
for word, freq in most_common[:top_n]:
print(f"{word}: {freq}")
# Input: Path to the text file
file_path = input("Enter the path to the text file: ")
# Display the most frequent words
display_most_frequent_words(file_path)
Program 14: To write a Python program to simulate elliptical orbits in Pygame.
Steps for the Simulation:
1. Initialize Pygame: Set up the Pygame window.
2. Define the Ellipse Parameters: Set the semi-major axis aaa and semi-minor axis bbb.
3. Compute Position: Use the parametric equations to calculate the position of the moving
object over time.
4. Update the Display: Draw the object at the calculated position and update the display to
animate the movement.
5. Handle Events: Allow the program to exit gracefully when the user closes the window.
Program:
import pygame
import math
# Initialize Pygame
pygame.init()
# Set up display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Elliptical Orbit Simulation")
# Set up colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Parameters for the ellipse
center_x, center_y = width // 2, height // 2 # Center of the screen
a = 200 # Semi-major axis
b = 100 # Semi-minor axis
# Time variables for animation
t = 0 # Parameter that changes over time
speed = 0.05 # Speed of the motion along the orbit
# Run the game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Clear screen
screen.fill(BLACK)
# Calculate the position of the moving object on the ellipse
x = center_x + a * math.cos(t)
y = center_y + b * math.sin(t)
# Draw the center of the orbit (sun)
pygame.draw.circle(screen, WHITE, (center_x, center_y), 10)
# Draw the moving object (planet)
pygame.draw.circle(screen, RED, (int(x), int(y)), 5)
# Update the display
pygame.display.update()
# Increment the parameter t for the next frame
t += speed
# Limit the frame rate
pygame.time.Clock().tick(60)
# Quit Pygame
pygame.quit()
Program 15: To write a Python program to bouncing ball in Pygame
In this program, we will simulate a bouncing ball in Pygame. The ball will move around the
screen and bounce off the walls when it hits them.
Steps:
1. Initialize Pygame: Set up the Pygame window and initialize necessary modules.
2. Define the Ball's Properties: Position, velocity, and color of the ball.
3. Handle the Ball's Movement: Update the ball's position by adding velocity and check
for boundary collisions.
4. Handle Collisions: When the ball hits any of the window boundaries, its velocity will be
reversed (bounce effect).
5. Run the Game Loop: Update the position of the ball and display the ball's movement.
Program:
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball Simulation")
# Set up colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
# Ball properties
ball_radius = 20
x = random.randint(ball_radius, width - ball_radius)
y = random.randint(ball_radius, height - ball_radius)
ball_color = RED
# Ball velocity (dx, dy) for movement
dx = random.choice([-4, 4]) # Random horizontal velocity
dy = random.choice([-4, 4]) # Random vertical velocity
# Set up the game clock
clock = pygame.time.Clock()
# Run the game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the ball
x += dx
y += dy
# Bounce the ball off the walls by reversing velocity
if x - ball_radius <= 0 or x + ball_radius >= width:
dx = -dx # Reverse horizontal velocity when hitting the wall
if y - ball_radius <= 0 or y + ball_radius >= height:
dy = -dy # Reverse vertical velocity when hitting the wall
# Fill the screen with black background
screen.fill(BLACK)
# Draw the ball
pygame.draw.circle(screen, ball_color, (x, y), ball_radius)
# Update the display
pygame.display.update()
# Set the frame rate (FPS)
clock.tick(60)
# Quit Pygame
pygame.quit()