CBS GROUP OF INSTITUTIONS
AFFILAITED TO MDU
Python Programming Lab
Practical File
Submitted by: Komal Rani
Course: BTech (CSE)
Registration No:2313061475
Subject Code: LC-CSE-215G
1
S.no
Name of the program
Page
no.
1.
Compute the GCD of two
numbers.
Find the square root of a
number (Newton's method)
3
2.
3.
Exponentiation (power of a
number)
4. Find the maximum of a list of
numbers
5. Linear search and Binary
search
6. Selection sort, Insertion sort
7. Merge sort
8. First n prime numbers
9. Multiply matrices
10. Programs that take command
line arguments (word count)
11. Find the most frequent words
in a text read from a file
Date
Remark/
signatur
e
4-5
6
7
8-10
11-12
13-14
15-16
17-18
19
20-21
2
Program 1
Aim: Compute the GCD of two numbers.
Code:
def hcf(a, b):
if(b == 0):
return a
else:
return hcf(b, a % b)
a = 89
b = 56
print("The GCD of 89 and 56 is : ", end="")
print(hcf(89, 56))
Output:
3
Program 2
Aim: Find the square root of a number (Newton's method)
Code:
def sqrt_newton(S, tolerance=1e-10, max_iterations=1000):
if S < 0:
raise ValueError("Cannot compute square root of a negative
number.")
if S == 0:
return 0
x = S / 2.0
for _ in range(max_iterations):
x_new = (x + S / x) / 2
if abs(x_new - x) < tolerance:
return x_new
x = x_new
return x
number = 25
result = sqrt_newton(number)
print(f"The square root of {number} is approximately: {result}")
4
Output:
5
Program 3
Aim: Exponentiation (power of a number)
Code:
def exponentiation(base, exponent):
return base ** exponent
# Example usage
base = 2
exponent = 3
result = exponentiation(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
Output:
6
Program 4
Aim: Find the maximum Of a list Of numbers
Code:
numbers = [3, 5, 7, 2, 8, 6, 1]
max_value = max(numbers)
print(f"The maximum value in the list is: {max_value}")
Output:
7
Program 5
Aim: Linear search and Binary search
Code:
Linear search:
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index
return -1
arr = [1, 2, 18, 30, 60, 45]
target = 60
result = linear_search(arr, target)
if result != -1:
print("Element found at index",result)
else:
print("Element not found in the array")
Output:
8
Binary search:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
high = mid-1
elif arr[mid] < x:
low = mid+1
return -1
arr = [ 12, 13, 14, 15, 30 ]
x = 30
result = binary_search(arr, x)
if result != -1:
print("Element is present at index" ,result)
else:
print("Element is not present in array")
9
Output:
10
Program 6
Aim: Selection sort, Insertion sort
Code:
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
numbers = [64, 25, 12, 22, 11]
sorted_numbers = selection_sort(numbers)
print("Sorted list:", sorted_numbers)
Output:
11
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
numbers = [12, 11, 13, 5, 6]
sorted_numbers = insertion_sort(numbers)
print("Sorted list:", sorted_numbers)
Output:
12
Program 7
Aim: Merge sort
Code:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
sorted_array = []
left_index = right_index = 0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
sorted_array.append(left[left_index])
left_index += 1
13
else:
sorted_array.append(right[right_index])
right_index += 1
sorted_array.extend(left[left_index:])
sorted_array.extend(right[right_index:])
return sorted_array
arr = [38, 27, 43, 3, 9, 82, 10]
print("Original array:", arr)
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)
Output:
14
Program 8
Aim: Merge sort
Code:
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def first_n_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
n = 10
primes = first_n_primes(n)
15
print(f"The first {n} prime numbers are: {primes}")
Output:
16
Program 9
Aim: Multiply matrices
Code:
def multiply_matrices(A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
raise ValueError("Number of columns of A must be equal to
number of rows of B")
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]
return result
A=[
[1, 2],
[3, 4]
17
]
B=[
[5, 6],
[7, 8]
]
result = multiply_matrices(A, B)
for row in result:
print(row)
Output:
18
Program 10
Aim: Programs that take command line arguments (word
count)
Code:
import sys
args = sys.argv[1:]
words = " ".join(args).split()
word_count = len(words)
print(f"Word count: {word_count}")
Output:
19
Program 11
Aim: Find the most frequent words in a text read from a file
Code:
file = open("sample.txt","r")
frequent_word = ""
frequency = 0
words = []
for line in file:
line_word = line.lower().replace(',','').replace('.','').split(" ");
for w in line_word:
words.append(w);
for i in range(0, len(words)):
count = 1;
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
20
if(count > frequency):
frequency = count;
frequent_word = words[i];
print("Most repeated word: " + frequent_word)
print("Frequency: " + str(frequency))
file.close();
output:
21