1.Start a Python interpreter and use it as a Calculator.
Program:
# Calculator Program in Python by using input() and format() func ons
#Prom ng input from the user
n1 = float(input("Enter the First Number: "))
n2 = float(input("Enter the Second Number: "))
#addi on
print("{} + {} = ".format(n1, n2))
print(n1 + n2)
#subtrac on
print("{} - {} = ".format(n1, n2))
print(n1 - n2)
#mul plica on
print("{} * {} = ".format(n1, n2))
print(n1 * n2)
#division
print("{} / {} = ".format(n1, n2))
print(n1 / n2)
OUTPUT:
Enter the First Number: 3
Enter the Second Number: 5
3.0 + 5.0 =
8.0
3.0 - 5.0 =
-2.0
3.0 * 5.0 =
15.0
3.0 / 5.0 =
0.6
=== Code Execu on Successful ===
1
2. Write a program to calculate compound interest when principal, rate and number of periods are given.
PROGRAM:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
me = float(input("Enter the me in years: "))
compound_interest = principal * ((1 + rate/100) ** me) - principal
print("The compound interest is:", compound_interest)
OUTPUT:
Enter the principal amount: 100000
Enter the rate of interest: 12
Enter the me in years: 1
The compound interest is: 12000.000000000015
=== Code Execu on Successful ===
***********************************************************************************************
3. Given coordinates (x1, y1), (x2, y2) find the distance between two points
PROGRAM:
# Python Program to Calculate Distance
# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calcula ng distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))
2
OUTPUT:
Enter x1: 5
Enter y1: 2
Enter x2: 3
Enter y2: 5
Distance = 3.605551
=== Code Execu on Successful ===
***********************************************************************************************
4. Read name, address, email and phone number of a person through keyboard and print the details.
PROGRAM:
# read name, address, contact and email from user and print them
print("Enter your name: ", end="")
name = input()
print("Enter your address: ", end="")
address = input()
print("Enter your contact: ", end="")
contact = input()
print("Enter your email: ", end="")
email = input()
print("Name: ", name)
print("Address: ", address)
print("Contact: ", contact)
print("Email: ", email)
OUTPUT:
Enter your name: Dheeraj
Enter your address: Hyderabad
Enter your contact: 9546716813
Enter your email: dheeraj@GMAIL.COM
Name: Dheeraj
Address: Hyderabad
Contact: 9546716813
Email: dheeraj@GMAIL.COM
=== Code Execu on Successful ===
3
5. Print the below triangle using for loop.
44
333
2222
11111
PROGRAM:
n = int (input(“Enter the no. of lines for the tri:” “))
for i in range (1, n+1);
for j in range (i);
if j== i-1;
print(n)
else,
print(n, end = “ “)
n = n-1
OUTPUT:
44
333
2222
11111
************************************************************************************************
6. Write a program to check whether the given input is digit or lowercase character or uppercase character or a
special character (use 'if-else-if' ladder)
PROGRAM:
def check_character(char):
if char.isdigit():
print(f"{char} is a digit.")
elif char.islower():
print(f"{char} is a lowercase character.")
elif char.isupper():
print(f"{char} is an uppercase character.")
else:
4
print(f"{char} is a special character.")
# Taking input from the user
input_char = input("Enter a character: ")
# Checking the type of character
check_character(input_char)
OUTPUT:
Enter a character: @
@ is a special character.
************************************************************************************************
7. Python Program to Print the Fibonacci sequence using while loop
PROGRAM:
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a posi ve integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
5
n2 = nth
count += 1
OUTPUT :
How many terms? 5
Fibonacci sequence:
*************************************************************************************************
8. Python program to print all prime numbers in a given interval (use break)
PROGRAM:
# Python program to display all the prime numbers within an interval
lower = 0
upper = 10
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
OUTPUT:
Prime numbers between 0 and 10 are:
6
9. Write a program to convert a list and tuple into arrays.
PROGRAM:
import numpy as np
list_data = [1, 2, 3, 4, 5]
array_from_list = np.array(list_data)
tuple_data = (6, 7, 8, 9, 10)
array_from_tuple = np.array(tuple_data)
print("List to Array:", array_from_list)
print("Tuple to Array:", array_from_tuple)
OUTPUT:
List to Array: [1 2 3 4 5]
Tuple to Array: [ 6 7 8 9 10]
*************************************************************************************************
10. Write a program to find common values between two arrays.
PROGRAM:
import numpy as np
ar1 = np.array([0, 1, 2, 3, 4])
ar2 = [1, 3, 4, 2]
# Common values between two arrays
print(np.intersect1d(ar1, ar2))
OUTPUT:
[1 2 3 4]
*************************************************************************************************
11. Write a func on called gcd that takes parameters a and b and returns their greatest common divisor.
PROGRAM:
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def hcf(a, b):
if(b == 0):
return a
else:
return hcf(b, a % b)
7
a = 60
b = 48
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
OUTPUT:
The gcd of 60 and 48 is : 12
*************************************************************************************************
12. Write a func on called palindrome that takes a string argument and returnsTrue if it is a palindrome and False
otherwise. Remember that you can use the built-in func on len to check the length of a string.
PROGRAM:
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
OUTPUT:
The string is a palindrome.
*************************************************************************************************
13. . Write a func on called is_sorted that takes a list as a parameter and returns True if the list is sorted in
ascending order and False otherwise.
PROGRAM:
def is_sorted(a):
for i in range(len(a)-1):
if a[i]<=a[i+1]:
return True
return False
8
print(is_sorted([3,4,4,8,2,5,6,2]))
OUTPUT:
True
*************************************************************************************************
14. Write a func on called has_duplicates that takes a list and returns True if there is any element that appears
more than once. It should not modify the original list.
PROGRAM:
def has_duplicates(a):
if len(a) !=len(set(a)):
return True
else:
return False
a=[1,2,3,4,5]
print(has_duplicates(a))
OUTPUT:
False
*************************************************************************************************
15. Write a func on called remove_duplicates that takes a list and returns a new list with only the unique elements
from the original. Hint: they don’t have to be in the same order
PROGRAM:
# Python code to remove duplicate elements
def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
# Driver Code
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))
OUTPUT:
[2, 4, 10, 20, 5]
9
16. Write a python code to read dic onary values from the user. Construct a func on to invert its content. i.e., keys
should be values and values should be keys.
PROGRAM:
def invert (D):
d1 = dict( )
for key in D.keys ( ) :
d1[ D[key]] = key
return d1
d = dict( )
n = int( input (“Enter the no. of key value pairs: “))
for i in range (i, n+1):
d[i] = input (“Enter a value : “)
print (“ The original dic onary : “ , d)
print (“ The invested dic onary : “, invest (d))
OUTPUT:
Enter the no .of key value : 5
Enter a value : A
Enter a value : B
Enter a value : C
Enter a value : D
Enter a value : E
The original dic onary :{1:’A’ , 2:’B’ , 3:’C’ , 4:’D’ , 5:’ E’}
The inversed dic onary :{‘A’:1 , ‘B’:2 , ‘C’:3 , ‘D’ :4 , ‘E’ :5}
************************************************************************************************
17. Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e
PROGRAM:
x = "APPLE"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))
10
OUTPUT:
'A,P,P,L,E,'
*************************************************************************************************
18. Remove the given word in all the places in a string?
PROGRAM:
a1 = "remove word from this"
a2 = a1.replace("word", '')
print(a2)
OUTPUT:
Remove from this
*************************************************************************************************
19. Write a func on that takes a sentence as an input parameter and replaces the first le er of every word with the
corresponding upper case le er and the rest of the le ers in the word by corresponding le ers in lower case without
using a built-in func on?
PROGRAM:
def proper (s):
L = s.split(“ “)
nl = [ ]
for word in L :
nl.append (word[0] .upper( ) + word [1: :] , lower(1)
retun nl
sent = input (“Enter a sentence: “)
new_L = proper (sent)
for w in new_L ;
print( w, end = “ “)
OUTPUT:
Enter a sentence : PAPER IS IN HAND
Paper Is In Hand
*************************************************************************************************
20. Writes a recursive func on that generates all binary strings of n-bit length
PROGRAM:
def print_binary_combina ons(n):
# Loop through all numbers from 0 to 2^n – 1
11
for i in range(1 << n):
# Convert the current number to a binary string of length n
binary_str = format(i, '0' + str(n) + 'b')
print(binary_str)
# Example usage
n=2
print_binary_combina ons(n)
OUTPUT:
00
01
10
11
*************************************************************************************************
WEEK-5
21. Write a python program that defines a matrix and prints.
PROGRAM:
Row = int(input("Enter the number of rows:"))
Column = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("enter the entries row wise:")
# For user input
# A for loop for row entries
for row in range(Row):
a = []
# A for loop for column entries
for column in range(Column):
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for row in range(Row):
for column in range(Column):
print(matrix[row][column], end=" ")
print()
12
OUTPUT:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries row wise:
56
78
*************************************************************************************************
22.Write a python program to perform addi on of two square matrices.
PROGRAM:
def add_matrices(mat1, mat2):
# Check if matrices are square
if len(mat1) != len(mat1[0]) or len(mat2) != len(mat2[0]):
raise ValueError("Matrices must be square matrices (same number of rows and columns)")
# Ini alize result matrix with zeros
size = len(mat1)
result = [[0] * size for _ in range(size)]
# Perform addi on
for i in range(size):
for j in range(size):
result[i][j] = mat1[i][j] + mat2[i][j]
return result
# Example usage:
if __name__ == "__main__":
# Example square matrices
matrix1 = [
13
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
try:
result = add_matrices(matrix1, matrix2)
print("Result of matrix addi on:")
for row in result:
print(row)
except ValueError as e:
print(e)
OUTPUT:
Result of matrix addi on:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
=== Code Execu on Successful ==
*************************************************************************************************
23.Write a python program to perform mul plica on of two square matrices.
Program:
def mul ply_matrices(mat1, mat2):
# Check if matrices are square
if len(mat1) != len(mat1[0]) or len(mat2) != len(mat2[0]):
raise ValueError("Matrices must be square matrices (same number of rows and columns)")
size = len(mat1)
result = [[0] * size for _ in range(size)]
14
# Perform mul plica on
for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
# Example usage:
if __name__ == "__main__":
# Example square matrices
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
try:
result = mul ply_matrices(matrix1, matrix2)
print("Result of matrix mul plica on:")
for row in result:
print(row)
except ValueError as e:
print(e)
OUTPUT:
Result of matrix mul plica on:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
=== Code Execu on Successful ===
15
24.How do you make a moduleive an example of construc on of a
module using different geometrical shapes and o? Gpera ons on them
as its func ons.
PROGRAM:
Crea ng a module in python involves crea ng a python file (module) with
func ons or classes that can be imported and used in other python scripts. Let’s
say, to create a module called ‘geometry.py’ that contains func ons shapes, etc...
Here’s how ‘geometry.py’ module can be structures
Import math
def rec_a(l, w):
return l*w
def rec_p(l, w):
return 2* (l+w)
def cir_a(radius ):
return (math.pi * r)
def tri_a (b, h):
return 0.5* b * h
Now, in another python script, import geometry
Length= 5
Width= 3
print(“rectangular area : “, geometry . cir_a (width))
this separate script imports the ‘geometry’ module and uses its func on to
perform calcula ons for different geometric shapes
16
25. Use the structure of excep on handling all general-purpose
excep ons.
PROGRAM:
Here’s a general purpose excep on handling structure that handles all excep ons:
try :
result = 10/0 #Zero Division error will raise
file = open (“non _existent .txt”, ‘r’) #file not found
except Excep on as e:
# This block catches any excep on in try blocks
Print (f”An error occured : {e}”)
else:
#This block exectes if no excep on occurs within the try block
Print(“ No excep ons occurred”)
finally :
#This block always occurs regardless of any situa on in the try block.
Print(“ finally block executed”)
17
Week-6
26. Write a func on called draw_rectangle that takes a Canvas and a
Rectangle as arguments and draws a representa on of the Rectangle
on the Canvas.
PROGRAM:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def set_pixel(self, x, y, char):
self.data[y][x] = char
def display(self):
for row in self.data:
print(''.join(row))
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw_rectangle(canvas, rectangle):
# Ensure rectangle dimensions are within canvas bounds
if (rectangle.x < 0 or rectangle.y < 0 or
18
rectangle.x + rectangle.width > canvas.width or
rectangle.y + rectangle.height > canvas.height):
raise ValueError("Rectangle dimensions exceed canvas bounds")
# Draw the top and bo om edges
for i in range(rectangle.width):
canvas.set_pixel(rectangle.x + i, rectangle.y, '-')
canvas.set_pixel(rectangle.x + i, rectangle.y + rectangle.height - 1, '-')
# Draw the le and right edges
for i in range(rectangle.height):
canvas.set_pixel(rectangle.x, rectangle.y + i, '|')
canvas.set_pixel(rectangle.x + rectangle.width - 1, rectangle.y + i, '|')
# Example usage:
if __name__ == "__main__":
# Create a canvas
canvas = Canvas(20, 10)
# Define a rectangle
rect = Rectangle(4, 2, 10, 5)
# Draw the rectangle on the canvas
draw_rectangle(canvas, rect)
# Display the canvas
canvas.display()
19
OUTPUT:
|--------|
| |
| |
| |
|--------|
=== Code Execu on Successful ===
******************************************************************
27. Add an a ribute named color to your Rectangle objects and modify
draw_rectangle so that it uses the color a ribute as the fill color
PROGRAM:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def set_pixel(self, x, y, char):
self.data[y][x] = char
def display(self):
for row in self.data:
print(''.join(row))
class Rectangle:
def __init__(self, x, y, width, height, color='*'):
self.x = x
20
self.y = y
self.width = width
self.height = height
self.color = color
def draw_rectangle(canvas, rectangle):
# Ensure rectangle dimensions are within canvas bounds
if (rectangle.x < 0 or rectangle.y < 0 or
rectangle.x + rectangle.width > canvas.width or
rectangle.y + rectangle.height > canvas.height):
raise ValueError("Rectangle dimensions exceed canvas bounds")
# Draw the filled rectangle
for i in range(rectangle.height):
for j in range(rectangle.width):
canvas.set_pixel(rectangle.x + j, rectangle.y + i, rectangle.color)
# Example usage:
if __name__ == "__main__":
# Create a canvas
canvas = Canvas(20, 10)
# Define a rectangle with color
rect = Rectangle(4, 2, 10, 5, color='*')
# Draw the rectangle on the canvas
draw_rectangle(canvas, rect)
# Display the canvas
canvas.display()
21
OUTPUT:
--------------------
| |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| |
--------------------
28. Write a func on called draw_point that takes a Canvas and a Point
as arguments and draws a representa on of the Point on the Canvas.
PROGRAM:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
22
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def draw_point(self, point):
# Check if the point is within the bounds of the canvas
if 0 <= point.x < self.width and 0 <= point.y < self.height:
# Represent the point with '*'
self.data[point.y][point.x] = '*'
def display(self):
for row in self.data:
print(' '.join(row))
def main():
canvas = Canvas(20, 10)
point = Point(5, 3)
canvas.draw_point(point)
print("Canvas with Point:")
canvas.display()
if __name__ == "__main__":
main()
OUTPUT:
Canvas with Point:
=== Code Execu on Successful ===
23
29. Define a new class called Circle with appropriate a ributes and
instan ate a few Circle objects. Write a func on called draw_circle
that draws circles on the canvas.
PROGRAM:
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def draw_point(self, point, char='*'):
# Check if the point is within the bounds of the canvas
if 0 <= point.x < self.width and 0 <= point.y < self.height:
self.data[point.y][point.x] = char
def draw_circle(self, circle):
# Midpoint circle drawing algorithm
24
cx, cy = circle.center.x, circle.center.y
radius = circle.radius
x = radius
y=0
decision = 1 - x
while y <= x:
self.draw_point(Point(cx + x, cy + y))
self.draw_point(Point(cx - x, cy + y))
self.draw_point(Point(cx + x, cy - y))
self.draw_point(Point(cx - x, cy - y))
self.draw_point(Point(cx + y, cy + x))
self.draw_point(Point(cx - y, cy + x))
self.draw_point(Point(cx + y, cy - x))
self.draw_point(Point(cx - y, cy - x))
y += 1
if decision <= 0:
decision += 2 * y + 1
else:
x -= 1
decision += 2 * (y - x) + 1
def display(self):
for row in self.data:
print(' '.join(row))
def main():
canvas = Canvas(20, 20)
25
# Example circles
circle1 = Circle(Point(8, 8), 5)
circle2 = Circle(Point(15, 10), 7)
# Draw circles on the canvas
canvas.draw_circle(circle1)
canvas.draw_circle(circle2)
print("Canvas with Circles:")
canvas.display()
if __name__ == "__main__":
main()
26
OUTPUT:
Canvas with Circles:
*
* *
* *
* *
* *
* *
* *
*
30. Write a Python program to demonstrate the usage of Method
Resolu on Order (MRO) in mul ple levels of Inheritances
PROGRAM:
class A:
def myname(self):
print(" I am a class A")
class B(A):
def myname(self):
print(" I am a class B")
class C(A):
def myname(self):
print("I am a class C")
# classes ordering
class D(B, C):
pass
27
d = D()
d.myname()
OUTPUT:
I am a class B
=== Code Execu on Successful ===
31. Write a python code to read a phone number and email-id from the
user and validate it for correctness.
PROGRAM:
import re
def validate_phone_number(phone_number):
# Regular expression pa ern for a valid phone number
pa ern = r'^(\+\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$'
return re.match(pa ern, phone_number) is not None
def validate_email(email):
# Regular expression pa ern for a valid email address
pa ern = r'^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$'
return re.match(pa ern, email) is not None
def main():
# Read phone number and email from the user
phone_number = input("Enter a phone number: ")
email = input("Enter an email address: ")
28
# Validate phone number
if validate_phone_number(phone_number):
print(f"Phone number '{phone_number}' is valid.")
else:
print(f"Phone number '{phone_number}' is not valid.")
# Validate email
if validate_email(email):
print(f"Email '{email}' is valid.")
else:
print(f"Email '{email}' is not valid.")
if __name__ == "__main__":
main()
OUTPUT:
Enter a phone number: 9959093361
Enter an email address: dheeraj@gmail.com
Phone number '9959093361' is valid.
Email 'dheeraj@gmail.com' is valid.
=== Code Execu on Successful ===
29
WEEK-7
32. Write a Python code to merge two given file contents into a third
file
PROGRAM:
def merge_files(file1_name, file2_name, output_file_name):
try:
# Open the first file for reading
with open(file1_name, 'r') as file1:
file1_content = file1.read()
# Open the second file for reading
with open(file2_name, 'r') as file2:
file2_content = file2.read()
# Open the third file for wri ng
with open(output_file_name, 'w') as output_file:
# Write the contents of the first file
output_file.write(file1_content)
# Write the contents of the second file
output_file.write(file2_content)
print(f"Merged contents of '{file1_name}' and '{file2_name}' into
'{output_file_name}' successfully.")
30
except FileNotFoundError:
print("One of the input files does not exist.")
except IOError:
print("Error occurred while reading or wri ng files.")
def main():
file1 = 'file1.txt'
file2 = 'file2.txt'
output_file = 'merged_file.txt'
merge_files(file1, file2, output_file)
if __name__ == "__main__":
main()
OUTPUT:
File1.txt
Contents of file1.
Line 2 of file1.
File2.txt
Contents of file2.
Line 2 of file2.
merged_file.txt
Contents of file1.
Line 2 of file1.
31
Contents of file2.
Line 2 of file2.
33. Write a Python code to open a given file and construct a func on to
check for given words present in it and display on found.
PROGRAM:
def check_words_in_file(file_path, words_to_check):
try:
with open(file_path, 'r') as file:
file_content = file.read()
for word in words_to_check:
if word in file_content:
print(f"Found '{word}' in the file.")
else:
print(f"'{word}' not found in the file.")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'sample_file.txt' # Replace with your file path
32
words_to_check = ['apple', 'banana', 'orange', 'pear']
check_words_in_file(file_path, words_to_check)
if __name__ == "__main__":
main()
OUTPUT:
sample_file.txt
This is a sample file for tes ng purposes.
It contains some words like apple, orange, and banana.
words_to_check = ['apple', 'banana', 'orange', 'pear']
Found 'apple' in the file.
Found 'banana' in the file.
Found 'orange' in the file.
'pear' not found in the file.
34. Write a Python code to Read text from a text file, find the word with
most number of occurrences.
PROGRAM:
import re
from collec ons import Counter
def find_most_common_word(file_path):
try:
33
# Open the file and read its contents
with open(file_path, 'r') as file:
text = file.read()
# Use regex to extract words from the text (including hyphenated words)
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
# Count the occurrences of each word
word_counts = Counter(words)
# Find the word with the highest count
most_common_word, count = word_counts.most_common(1)[0]
print(f"The most common word in '{file_path}' is '{most_common_word}'
with {count} occurrences.")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'sample_text.txt' # Replace with your file path
find_most_common_word(file_path)
if __name__ == "__main__":
34
main()
OUTPUT:
sample_text.txt
This is a sample text file. It contains some words like apple, banana, apple,
orange, banana, apple.
file_path = 'sample_text.txt
The most common word in 'sample_text.txt' is 'apple' with 3 occurrences.
35
35. Write a func on that reads a file file1 and displays the number of
words, number of vowels, blank spaces, lower case le ers and
uppercase le ers.
PROGRAM:
def analyze_file(file_path):
try:
with open(file_path, 'r') as file:
# Read the en re content of the file
content = file.read()
# Calculate the number of words
words = content.split()
num_words = len(words)
# Calculate the number of vowels
vowels = 'aeiouAEIOU'
num_vowels = sum(content.count(vowel) for vowel in vowels)
# Calculate the number of blank spaces
num_spaces = content.count(' ')
# Calculate the number of lowercase le ers
num_lower = sum(1 for char in content if char.islower())
# Calculate the number of uppercase le ers
num_upper = sum(1 for char in content if char.isupper())
# Print the analysis results
36
print(f"Number of words: {num_words}")
print(f"Number of vowels: {num_vowels}")
print(f"Number of blank spaces: {num_spaces}")
print(f"Number of lowercase le ers: {num_lower}")
print(f"Number of uppercase le ers: {num_upper}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'file1.txt' # Replace with your file path
analyze_file(file_path)
if __name__ == "__main__":
main()
OUTPUT:
file1.txt
This is a Sample TEXT file. It contains some words with vowels like apple, banana,
orange.
file_path = 'file1.txt
Number of words: 16
Number of vowels: 33
Number of blank spaces: 16
Number of lowercase le ers: 54
Number of uppercase le ers: 9
37
WEEK-8
36. Import numpy, Plotpy and Scipy and explore their func onali es.
PROGRAM:
import scipy.op mize as opt
from scipy.integrate import quad
# Example 1: Numerical Integra on
def integrand(x):
return np.exp(-x**2)
result, _ = quad(integrand, 0, np.inf)
print("Numerical Integra on Result:", result)
# Example 2: Op miza on
def objec ve(x):
return x**2 + 10*np.sin(x)
result = opt.minimize(objec ve, x0=0)
print("\nOp miza on Result:")
print("Minimum value:", result.fun)
print("Op mal x:", result.x)
OUTPUT:
Numerical Integra on Result: 0.8862269254527579
Op miza on Result:
Minimum value: -7.945823375615284
Op mal x: [-1.30644001]
38
37. Install NumPy package with pip and explore it
PROGRAM:
import numpy as np
# Crea ng a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(arr1)
# Crea ng a 2D array (matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array (Matrix):")
print(arr2)
OUTPUT:
1D Array:
[1 2 3 4 5]
2D Array (Matrix):
[[1 2 3]
[4 5 6]]
=== Code Execu on Successful ===
39
38. Write a program to implement Digital Logic Gates – AND, OR, NOT,
EX-OR.
PROGRAM:
# Define logic gates func ons
def AND_gate(input1, input2):
if input1 == 1 and input2 == 1:
return 1
else:
return 0
def OR_gate(input1, input2):
if input1 == 1 or input2 == 1:
return 1
else:
return 0
def NOT_gate(input1):
if input1 == 1:
return 0
else:
return 1
def XOR_gate(input1, input2):
if input1 != input2:
return 1
else:
return 0
# Test the logic gates
40
def main():
input1 = 1
input2 = 0
# AND gate
print(f"AND gate ({input1}, {input2}): {AND_gate(input1, input2)}")
# OR gate
print(f"OR gate ({input1}, {input2}): {OR_gate(input1, input2)}")
# NOT gate
print(f"NOT gate ({input1}): {NOT_gate(input1)}")
print(f"NOT gate ({input2}): {NOT_gate(input2)}")
# XOR gate
print(f"XOR gate ({input1}, {input2}): {XOR_gate(input1, input2)}")
if __name__ == "__main__":
main()
OUTPUT:
AND gate (1, 0): 0
OR gate (1, 0): 1
NOT gate (1): 0
NOT gate (0): 1
XOR gate (1, 0): 1
=== Code Execu on Successful ===
41
39. Write a program to implement Half Adder, Full Adder, and Parallel
Adder.
PROGRAM:
def half_adder(bit1, bit2):
sum_ = bit1 ^ bit2 # XOR gives the sum
carry = bit1 & bit2 # AND gives the carry
return sum_, carry
def full_adder(bit1, bit2, carry_in):
sum_ = (bit1 ^ bit2) ^ carry_in # XOR of inputs and carry gives the sum
carry_out = (bit1 & bit2) | (carry_in & (bit1 ^ bit2)) # OR of ANDs gives the
carry-out
return sum_, carry_out
def parallel_adder(num1, num2):
max_len = max(len(num1), len(num2))
num1 = [0] * (max_len - len(num1)) + num1 # Zero-pad to make lengths equal
num2 = [0] * (max_len - len(num2)) + num2
result = []
carry = 0
for i in range(max_len - 1, -1, -1):
sum_, carry = full_adder(num1[i], num2[i], carry)
42
result.insert(0, sum_)
if carry:
result.insert(0, carry)
return result
def test_adders():
# Test Half Adder
bit1 = 1
bit2 = 0
sum_, carry = half_adder(bit1, bit2)
print(f"Half Adder: {bit1} + {bit2} = {sum_} (Sum), {carry} (Carry)")
# Test Full Adder
bit1 = 1
bit2 = 1
carry_in = 1
sum_, carry_out = full_adder(bit1, bit2, carry_in)
print(f"Full Adder: {bit1} + {bit2} + {carry_in} = {sum_} (Sum), {carry_out}
(Carry-Out)")
# Test Parallel Adder
num1 = [1, 0, 1] # 5 in binary
num2 = [1, 1, 1] # 7 in binary
result = parallel_adder(num1, num2)
print(f"Parallel Adder: {num1} + {num2} = {result} (Result)")
43
if __name__ == "__main__":
test_adders()
OUTPUT:
Half Adder: 1 + 0 = 1 (Sum), 0 (Carry)
Full Adder: 1 + 1 + 1 = 1 (Sum), 1 (Carry-Out)
Parallel Adder: [1, 0, 1] + [1, 1, 1] = [1, 1, 0, 0] (Result)
=== Code Execu on Successful ===
44