Python Practical File
Python Practical File
# If the difference between new and old guess is small enough, stop
if abs(x_new - x) < tolerance:
return x_new
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
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
def selection_sort(arr):
n = len(arr)
# 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
def merge_sort(arr):
# Base case: If the array has one or zero elements, it's already sorted
if len(arr) <= 1:
return arr
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
return C
A=[
[1, 2],
[3, 4]
]
B=[
[5, 6],
[7, 8]
]
result = multiply_matrices(A, B)
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
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 main():
if len(sys.argv) != 2:
print("Usage: python most_frequent_words.py <filename>")
sys.exit(1)
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
# 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
# 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)
import pygame
# initialize pygame
pygame.init()
# 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()
# 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()