0% found this document useful (0 votes)
15 views

Python Practical File

The document contains a list of programming tasks along with their implementations in Python, covering topics such as GCD computation, square root calculation using Newton's method, exponentiation, searching algorithms, sorting algorithms, and matrix multiplication. It also includes programs for command line argument handling and simulations using Pygame. Each program is presented with its respective code and functionality.

Uploaded by

alok singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Practical File

The document contains a list of programming tasks along with their implementations in Python, covering topics such as GCD computation, square root calculation using Newton's method, exponentiation, searching algorithms, sorting algorithms, and matrix multiplication. It also includes programs for command line argument handling and simulations using Pygame. Each program is presented with its respective code and functionality.

Uploaded by

alok singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

S.

No Programs Date Signature


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
7 INSERTION SORT
8 MERGE SORT
9 FIRST N PRIME NUMBERS
10 MULTIPLY MATRICES
11 PROGRAMS THAT TAKE
COMMAND LINE ARGUMENTS
(WORD COUNT)
12 FIND THE MOST FREQUENT
WORDS IN A TEXT READ FROM
A FILE.
13 SIMULATE ELLIPTICAL ORBITS
IN PYGAME
14 SIMULATE BOUNCING BALL
USING PYGAME
PROGRAM-1: COMPUTE THE GCD OF TWO
NUMBERS

def gcd(a, b):


# Base case: if both numbers are the same, that is the GCD
if a == b:
return a
# If a > b, subtract b from a
elif a > b:
return gcd(a - b, b)
# If b > a, subtract a from b
else:
return gcd(a, b - a)
x = int(input(“Enter a number:”))
y = int(input(“Enter a number:”))
print("GCD of", x, "and", y, "is:", gcd(x, y))
PROGRAM-2: FIND THE SQUARE ROOT OF A
NUMBER (NEWTON ‘S METHOD)

def sqrt_newton(N, tolerance=1e-10, max_iter=100):


# Starting guess, we can use N itself or N/2
x = N / 2.0

# Iterate using Newton's method


for _ in range(max_iter):
# Apply the Newton's method formula
x_new = 0.5 * (x + N / x)

# If the difference between new and old guess is small enough, stop
if abs(x_new - x) < tolerance:
return x_new

# Update guess for next iteration


x = x_new
return x # Return the approximated result after max iterations
number = 25
result = sqrt_newton(number)
print(f"The square root of {number} is approximately {result}")
PROGRAM-3: EXPONENTIATION (POWER OF A
NUMBER)

def power(base, exp):


# Base case: exp = 0, any number to the power of 0 is 1
if exp == 0:
return 1
# If exponent is negative, calculate power of positive exponent and
take reciprocal
elif exp < 0:
return 1 / power(base, -exp)
# If exponent is even, use exponentiation by squaring
elif exp % 2 == 0:
half = power(base, exp // 2)
return half * half
# If exponent is odd
else:
return base * power(base, exp - 1)

base = 2
exponent = 10
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is {result}")
PROGRAM-4: FIND THE MAXIMUM OF A LIST OF
NUMBERS

# Function to find the maximum in a list using a loop


def find_max(numbers):
max_value = numbers[0]
for num in numbers:
if num > max_value:
max_value = num
return max_value

# Take user input for a list of numbers


user_input = input("Enter a list of numbers separated by spaces: ")

# Convert the input string into a list of integers


numbers = [int(num) for num in user_input.split()]

# Find the maximum value in the list


max_value = find_max(numbers)

# Print the result


print(f"The maximum value in the list is: {max_value}")
PROGRAM-5: LINEAR SEARCH & BINARY SEARCH

def linear_search(arr, target):


# Iterate through each element in the list
for i in range(len(arr)):
if arr[i] == target:
return i # Target found, return the index
return -1 # Target not found

numbers = [5, 3, 9, 1, 6, 7, 2]
target = int(input("Enter a number to search: "))
result = linear_search(numbers, target)

if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found.")
def binary_search(arr, target):
low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2 # Find the middle index
if arr[mid] == target:
return mid # Target found
elif arr[mid] < target:
low = mid + 1 # Search the right half
else:
high = mid - 1 # Search the left half

return -1 # Target not found


numbers = [1, 3, 5, 6, 7, 9] # Sorted list
target = int(input("Enter a number to search: "))
result = binary_search(numbers, target)
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found.")
PROGRAM-6: SELECTION SORT

def selection_sort(arr):
n = len(arr)

# Iterate over each element of the list


for i in range(n):
# Find the smallest element in the remaining unsorted portion of the
list
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j

# Swap the found minimum element with the first element of the
unsorted portion
arr[i], arr[min_index] = arr[min_index], arr[i]
numbers = [64, 25, 12, 22, 11]
print("Original list:", numbers)
selection_sort(numbers)
print("Sorted list:", numbers)
PROGRAM-7: INSERTION SORT

def insertion_sort(arr):
# Start from the second element (index 1)
for i in range(1, len(arr)):
key = arr[i] # The element to be inserted
j = i - 1 # The index of the previous element

# Move elements of arr[0..i-1] that are greater than key


# to one position ahead of their current position
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1

# Insert the key at the correct position


arr[j + 1] = key
numbers = [64, 25, 12, 22, 11]
print("Original list:", numbers)
insertion_sort(numbers)
print("Sorted list:", numbers)
PROGRAM-8: MERGE SORT

def merge_sort(arr):
# Base case: If the array has one or zero elements, it's already sorted
if len(arr) <= 1:
return arr

# Step 1: Divide the array into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

# Step 2: Recursively sort each half


left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

# Step 3: Merge the two sorted halves


return merge(left_half, right_half)

def merge(left, right):


sorted_array = []
i=j=0
# Merge the two arrays until one of them is exhausted
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_array.append(left[i])
i += 1
else:
sorted_array.append(right[j])
j += 1

# If there are any remaining elements in left, add them


while i < len(left):
sorted_array.append(left[i])
i += 1

# If there are any remaining elements in right, add them


while j < len(right):
sorted_array.append(right[j])
j += 1

return sorted_array
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)
PROGRAM-9: FIRST N PRIME NUMBERS
import math
def is_prime(num):
"""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):
"""Return the first N prime numbers."""
primes = []
num = 2 # Start checking from the first prime number
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
n = int(input("ENTER N:"))
primes = first_n_primes(n)
print(f"The first {n} prime numbers are: {primes}")
PROGRAM-10: MULTIPLY MATRICES

def multiply_matrices(A, B):


# Get dimensions of A and B
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])

# Check if multiplication is possible (columns of A == rows of B)


if cols_A != rows_B:
raise ValueError("Number of columns of A must be equal to
number of rows of B.")

# Initialize result matrix C with zeros


C = [[0] * cols_B for _ in range(rows_A)]

# Perform matrix multiplication


for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A): # or range(rows_B), since cols_A ==
rows_B
C[i][j] += A[i][k] * B[k][j]

return C

A=[
[1, 2],
[3, 4]
]

B=[
[5, 6],
[7, 8]
]

result = multiply_matrices(A, B)

# Printing the result


for row in result:
print(row)
PROGRAM-11: PROGRAMS THAT TAKE COMMAND
LINE ARGUMENTS (WORD COUNT)

import sys

def count_words_in_file(filename):
"""Count the number of words in a file."""
try:
with open(filename, 'r') as file:
# Read the file content and split it into words
text = file.read()
words = text.split() # Default split by whitespace (spaces,
newlines, etc.)
return len(words)
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
return 0

def main():
if len(sys.argv) != 2:
print("Usage: python word_count.py <filename>")
sys.exit(1) # Exit the program if incorrect number of arguments

filename = sys.argv[1] # The first command-line argument is the file


name
word_count = count_words_in_file(filename)
print(f"The file '{filename}' contains {word_count} words.")

if __name__ == "__main__":
main()
PROGRAM-12: FIND THE MOST FREQUENT WORDS
IN A TEXT READ FROM A FILE.

import sys
from collections import Counter
import re

def count_most_frequent_words(filename, top_n=10):


"""Count the most frequent words in the given file."""
try:
with open(filename, 'r') as file:
# Read the entire file content
text = file.read()

# Convert the text to lowercase to make the counting case-


insensitive
text = text.lower()

# Use regular expression to extract words (remove punctuation)


words = re.findall(r'\b\w+\b', text)

# Count word frequencies using Counter


word_counts = Counter(words)

# Get the most common 'top_n' words


most_common_words = word_counts.most_common(top_n)
return most_common_words
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
return []

def main():
if len(sys.argv) != 2:
print("Usage: python most_frequent_words.py <filename>")
sys.exit(1)

filename = sys.argv[1] # The first command-line argument is the file


name
most_common_words = count_most_frequent_words(filename)

if most_common_words:
print("Most frequent words in the file:")
for word, count in most_common_words:
print(f"{word}: {count}")

if __name__ == "__main__":
main()
PROGRAM-13: SIMULATE ELLIPTICAL ORBITS IN
PYGAME

import pygame
import math

# initialize the pygame


pygame.init()
# define width of screen
width = 1000
# define height of screen
height = 600
screen_res = (width, height)

pygame.display.set_caption("GFG Elliptical orbit")


screen = pygame.display.set_mode(screen_res)

# define colors in RGB format


# These colors will be used in our game
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
cyan = (0, 255, 255)

# centers of screen
X_center = width//2
Y_center = height//2

# radius of ellipse
# X_ellipse is major radius of ellipsis
X_ellipse = 400
# Y_ellipse is minor radius of ellipsis
Y_ellipse = 225

# pygame.time.Clock() will be used further


# in the game loop to control
# the speed of the planet.
clock = pygame.time.Clock()
while True:
for degree in range(0, 360, 1):
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()

# fill black color on screen


screen.fill([0, 0, 0])

# We will find coordinates of 2 planet


# that will rotate in same ellipse
# calculate coordinates of planet 1
# x_planet is x coordinate
x_planet_1 = int(math.cos(degree * 2 * math.pi/360)
* X_ellipse) + X_center
# y_planet is y coordinate
y_planet_1 = int(math.sin(degree * 2 * math.pi/360)
* Y_ellipse) + Y_center
# calculate coordinates of planet 2
# As we want our planets to be opposite to
# each other so we will maintain a difference
# of 180 degrees between then
degree_2 = degree+180
# degree will be always between 0 and 360
if degree > 180:
degree_2 = degree-180
# x_planet is x coordinate
x_planet_2 = int(math.cos(degree_2 * 2 * math.pi/360)
* X_ellipse) + X_center
# y_planet is y coordinate
y_planet_2 = int(math.sin(degree_2 * 2 * math.pi/360)
* Y_ellipse) + Y_center

# draw circle in center of screen


pygame.draw.circle(surface=screen, color=red, center=[
X_center, Y_center], radius=60)

# draw ellipse
# Coordinate of left topmost point is (100,75)
# width of ellipse = 2*(major radius of ellipse)
# height of ellipse = 2*(minor radius of ellipse)
pygame.draw.ellipse(surface=screen, color=green,
rect=[100, 75, 800, 450],
width=1)

# draw both planets


# x_planet_1, y_planet_1, x_planet_2
# and y_planet_2 are calculated above
pygame.draw.circle(surface=screen, color=blue, center=[
x_planet_1, y_planet_1], radius=40)
pygame.draw.circle(surface=screen, color=cyan, center=[
x_planet_2, y_planet_2], radius=40)

# Frame Per Second /Refresh Rate


clock.tick(5)
# update screen
pygame.display.flip()
PROGRAM-14: SIM ULATE BOUNCING BALL USING
PYGAME

import pygame
# initialize pygame
pygame.init()

# define width of screen


width = 1000
# define height of screen
height = 600
screen_res = (width, height)

pygame.display.set_caption("GFG Bouncing game")


screen = pygame.display.set_mode(screen_res)

# define colors
red = (255, 0, 0)
black = (0, 0, 0)

# define ball
ball_obj = pygame.draw.circle(
surface=screen, color=red, center=[100, 100], radius=40)
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]

# game loop
while True:
# event loop
for event in pygame.event.get():
# check if a user wants to exit the game or not
if event.type == pygame.QUIT:
exit()

# fill black color on screen


screen.fill(black)

# move the ball


# Let center of the ball is (100,100) and the speed is (1,1)
ball_obj = ball_obj.move(speed)
# Now center of the ball is (101,101)
# In this way our wall will move

# if ball goes out of screen then change direction of movement


if ball_obj.left <= 0 or ball_obj.right >= width:
speed[0] = -speed[0]
if ball_obj.top <= 0 or ball_obj.bottom >= height:
speed[1] = -speed[1]

# draw ball at new centers that are obtained after moving ball_obj
pygame.draw.circle(surface=screen, color=red,
center=ball_obj.center, radius=40)

# update screen
pygame.display.flip()

You might also like