Python Lab Manual (CS-506)
Python Lab Manual (CS-506)
Jabalpur
AIML
Practical File
NAME:
ENROLLMENTNUMBER:
BRANCH: CSE-3
Submitted to
Prof. Vikash Verma
Algorithm:
Program:
"""
""" while b != 0:
a, b = b, a % b
return a
# Finding GCD
Program:
"""
"""
if n < 0:
# Initial guess
x = n / 2 if n != 0 else 0
while True:
next_x = 0.5 * (x + n / x)
break
x = next_x
return next_x
try:
sqrt_value = newton_sqrt(number)
except ValueError as e:
print(e)
Program:
"""
"""
result = 1
if exponent >= 0:
for _ in range(exponent):
result *= base
else:
for _ in range(-exponent):
result *= base
result = 1 / result
return result
# Calculating exponentiation
Program:
def find_maximum(numbers):
"""
"""
max_num = numbers[0]
max_num = num
return max_num
try:
numbers = list(map(float, input("Enter numbers separated by spaces: ").split()))
max_value = find_maximum(numbers)
except ValueError as e:
print(e)
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:
"""
"""
if num == target:
try:
if result != -1:
print(f"The target {target} is found at index {result}.")
else:
except ValueError:
"""
"""
if numbers[mid] == target:
else:
try:
if result != -1:
else:
except ValueError:
Program:
def selection_sort(numbers):
"""
"""
n = len(numbers)
for i in range(n):
min_index = i
min_index = j
return numbers
sorted_numbers = selection_sort(numbers)
except ValueError:
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
Insertion Sort builds the sorted list one element at a time by inserting each element into its
correct position:
Program:
def insertion_sort(numbers):
"""
"""
n = len(numbers)
key = numbers[i]
j=i-1
numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
return numbers
# Input from the user
try:
sorted_numbers = insertion_sort(numbers)
except ValueError:
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
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:
"""
"""
if len(numbers) > 1:
mid = len(numbers) // 2
left_half = numbers[:mid]
right_half = numbers[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
numbers[k] = left_half[i]
i += 1
else:
numbers[k] = right_half[j]
j += 1
k += 1
numbers[k] = left_half[i]
i += 1
k += 1
numbers[k] = right_half[j]
j += 1
k += 1
return numbers
sorted_numbers = merge_sort(numbers)
except ValueError:
The sorted list is: [11, 12, 22, 25, 34, 64, 90]
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):
"""
"""
if num <= 1:
return False
if num % i == 0:
return False
return True
def first_n_primes(n):
"""
"""
primes = []
if is_prime(num):
primes.append(num)
num += 1
return primes
try:
primes = first_n_primes(n)
except ValueError:
The first 10 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
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:
"""
"""
if len(A[0]) != len(B):
return result
# Input matrices
try:
# Matrix A
A = []
for i in range(rows_A):
A.append(row)
# Matrix B
if cols_A != rows_B:
else:
B = []
for i in range(rows_B):
B.append(row)
# Multiply matrices
result = multiply_matrices(A, B)
except ValueError:
123
456
78
9 10
11 12
58 64
139 154.
Program:
import sys
def main():
if len(sys.argv) < 2:
sys.exit(1)
try:
numbers = [int(arg) for arg in sys.argv[1:]]
total = sum(numbers)
except ValueError:
if __name__ == "__main__":
main()
python script_name.py 10 20 30
Argument 0: script_name.py
Argument 1: 10
Argument 2: 20
Argument 3: 30
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
def process_text(file_path):
"""
Function to read a file, clean the text, and find the most frequent words.
"""
try:
text = file.read()
text = text.lower()
words = text.split()
# Count the frequency of each word using Counter
word_count = Counter(words)
most_common = word_count.most_common()
return most_common
except FileNotFoundError:
return []
"""
"""
most_common = process_text(file_path)
if most_common:
print(f"{word}: {freq}")
display_most_frequent_words(file_path)
Program:
import pygame
import math
# Initialize Pygame
pygame.init()
# Set up display
# Set up colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
running = True
while running:
# Handle events
if event.type == pygame.QUIT:
running = False
# Clear screen
screen.fill(BLACK)
x = center_x + a * math.cos(t)
y = center_y + b * math.sin(t)
pygame.display.update()
t += speed
pygame.time.Clock().tick(60)
# Quit Pygame
pygame.quit()
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
# Set up colors
RED = (255, 0, 0)
BLACK = (0, 0, 0)
# Ball properties
ball_radius = 20
ball_color = RED
clock = pygame.time.Clock()
running = True
while running:
# Handle events
if event.type == pygame.QUIT:
running = False
x += dx
y += dy
# Bounce the ball off the walls by reversing velocity
screen.fill(BLACK)
pygame.display.update()
clock.tick(60)
# Quit Pygame
pygame.quit()