J.
P Institute of Engineering and
Technology
Mini Project
Python-File organizer
session : 2022 – 2026
Date : 5th DEC 2023
Submitted by :
Name : Priti kumari sah
Course : B.tech , I.T
Semester : 3rd
Roll : 2102820130014
Submitted to : Shikha Ma’am
Signature :
Table of Contents
1. Print number of command line arguments...................3
2. Matrix multiplication...................................................4
3. Find GCD of two numbers..........................................6
4.Find the number of most frequent word in a file..........7
5. Find square root of a number by newton’s method.....8
6. Find power of a number...............................................9
7. Find maximum in a list..............................................10
8. Implement linear search.............................................11
9. Implement binary search............................................12
10. Implement selection sort..........................................13
11. Implement insertion sort..........................................14
12. Implement merge sort..............................................15
13. Find first n prime numbers......................................17
14. Simulate a bouncing ball in Pygame.......................18
1. Print number of command line arguments.
import sys
def main():
arguments = sys.argv[1:]
# Print the number of arguments
num_arguments = len(arguments)
print(f"Number of arguments: {num_arguments}")
if __name__ == "__main__":
main()
input : python3 file.py arg1 arg2 arg3
output : 3
2. Matrix multiplication
def matrix_multiplication(matrix1, matrix2):
result = []
rows1 = len(matrix1)
cols1 = len(matrix1[0])
rows2 = len(matrix2)
cols2 = len(matrix2[0])
if cols1 != rows2:
print("Matrix multiplication is not possible.")
return None
for i in range(rows1):
row = []
for j in range(cols2):
value = 0
for k in range(cols1):
value += matrix1[i][k] * matrix2[k][j]
row.append(value)
result.append(row)
return result
def print_matrix(matrix):
for row in matrix:
print(row)
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
result_matrix = matrix_multiplication(matrix1, matrix2)
if result_matrix:
print("Matrix 1:")
print_matrix(matrix1)
print("\nMatrix 2:")
print_matrix(matrix2)
print("\nResult Matrix:")
print_matrix(result_matrix)
output:
Matrix 1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix 2:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Result Matrix:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
3. Find GCD of two numbers.
def gcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is {result}")
output:
Enter the first number: 48
Enter the second number: 18
The GCD of 48 and 18 is 6.
4.Find the number of most frequent word in a file.
import re
from collections import Counter
def most_frequent_word(filename):
with open(filename, 'r') as file:
text = file.read()
words = re.findall(r'\b\w+\b', text.lower()) # Extract
words and convert to lowercase
word_counts = Counter(words)
most_common_word, frequency =
word_counts.most_common(1)[0]
return most_common_word, frequency
filename = "your_text_file.txt" # Replace with the path to
your text file
most_common_word, frequency =
most_frequent_word(filename)
print(f"The most frequent word is '{most_common_word}'
with a frequency of {frequency}.")
output:
Enter the name of the text file: sample.txt
The most frequent word is 'the' with a frequency of 3.
5. Find square root of a number by newton’s method.
def newton_sqrt(number, iterations=10):
x = number # Initial guess
for _ in range(iterations):
x = (x + number / x) / 2
return x
# Input: The number for which you want to find the square
root
number = float(input("Enter a number: "))
# Input: Number of iterations for Newton's method
(optional)
iterations = int(input("Enter the number of iterations
(default is 10): ") or "10")
result = newton_sqrt(number, iterations)
print(f"The square root of {number} is approximately
{result:.6f}")
6. Find power of a number.
def iterative_power(base, exponent):
result = 1
for _ in range(exponent):
result *= base
return result
# Input: Base and exponent
base = float(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = iterative_power(base, exponent)
print(f"{base} raised to the power of {exponent}: {result}")
output:
Enter the base: 2
Enter the exponent: 5
2 raised to the power of 5 : 32
7. Find maximum in a list.
def find_maximum(numbers):
if not numbers:
return None
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
return maximum
# Input: List of numbers
numbers = input("Enter a list of numbers separated by
spaces: ").split()
numbers = [float(num) for num in numbers] # Convert to
floats
maximum = find_maximum(numbers)
if maximum is not None:
print(f"The maximum value is: {maximum}")
else:
print("The list is empty, so there is no maximum value.")
input list :[1,5,2,5,2,10]
output : 10
8. Implement linear search.
def linear_search(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1 # Element not found
# Input: List of elements and the target element to search
elements = input("Enter a list of elements separated by
spaces: ").split()
target = input("Enter the element to search for: ")
# Perform linear search
index = linear_search(elements, target)
if index != -1:
print(f"Element '{target}' found at index {index}")
else:
print(f"Element '{target}' not found in the list")
output:
Enter a list of elements separated by spaces: 10 20 30 40 50
Enter the element to search for: 30
Element '30' found at index 2
9. Implement binary search.
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Element not found
elements = input("Enter a sorted list of elements separated
by spaces: ").split()
elements = [int(element) for element in elements] #
Convert to integers
target = int(input("Enter the element to search for: "))
index = binary_search(elements, target)
if index != -1:
print(f"Element '{target}' found at index {index}")
else:
print(f"Element '{target}' not found in the list")
output : Enter a list : 10 20 30 40 50
Enter the element to search for: 30
Element '30' found at index 2
10. Implement selection sort.
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
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]
# Input: List of numbers
numbers = input("Enter a list of numbers separated by
spaces: ").split()
numbers = [float(num) for num in numbers] # Convert to
floats
selection_sort(numbers)
print("Sorted list:", numbers)
output:
Enter a list of numbers separated by spaces: 5 2 9 1 5
Sorted list: [1, 2, 5, 5, 9]
11. Implement insertion sort.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Input: List of numbers
numbers = input("Enter a list of numbers separated by
spaces: ").split()
numbers = [float(num) for num in numbers] # Convert to
floats
insertion_sort(numbers)
print("Sorted list:", numbers)
output:
Enter a list of numbers separated by spaces: 5 2 9 1 5
Sorted list: [1, 2, 5, 5, 9]
12. Implement merge sort.
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
return merge(left_half, right_half)
def merge(left, right):
result = []
left_index, right_index = 0, 0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result.extend(left[left_index:])
result.extend(right[right_index:])
return result
# Input: List of numbers
numbers = input("Enter a list of numbers separated by
spaces: ").split()
numbers = [float(num) for num in numbers] # Convert to
floats
sorted_numbers = merge_sort(numbers)
print("Sorted list:", sorted_numbers)
output:
Enter a list of numbers separated by spaces: 5 2 9 1 5
Sorted list: [1, 2, 5, 5, 9]
13. Find first n prime numbers.
def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i=5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def generate_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
n = int(input("Enter the number of prime numbers to
generate: "))
prime_numbers = generate_primes(n)
output:
Enter the number of prime numbers to generate: 5
The first 5 prime numbers are: [2, 3, 5, 7, 11]
14. Simulate a bouncing ball in Pygame.
import pygame
import sys
# Initialize Pygame
pygame.init()
# Window dimensions
width = 800
height = 600
# Colors
white = (255, 255, 255)
# Ball properties
ball_radius = 20
ball_color = (0, 0, 255)
ball_speed = [5, 5] # Initial speed (x, y)
# Create the window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball Simulation")
# Create the ball rect
ball_rect = pygame.Rect(width // 2 - ball_radius, height // 2
- ball_radius, ball_radius * 2, ball_radius * 2)
# Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Move the ball
ball_rect.x += ball_speed[0]
ball_rect.y += ball_speed[1]
# Bounce when hitting walls
if ball_rect.left <= 0 or ball_rect.right >= width:
ball_speed[0] = -ball_speed[0]
if ball_rect.top <= 0 or ball_rect.bottom >= height:
ball_speed[1] = -ball_speed[1]
# Clear the screen
screen.fill(white)
# Draw the ball
pygame.draw.circle(screen, ball_color, ball_rect.center,
ball_radius)
# Update the display
pygame.display.flip()
# Control the frame rate
pygame.time.Clock().tick(60)