0% found this document useful (0 votes)
9 views27 pages

Python Programs - 250128 - 140055

The document outlines various Python programming tasks, including calculating test averages, creating a Money class with operator overloading, generating Fibonacci numbers, analyzing string similarity, classifying hospital test results, counting examination failures, and maintaining a telephone directory for employees. Each task includes an aim, program code, algorithms, and sample outputs demonstrating the functionality. The programs effectively address their respective objectives while providing error handling and user interaction.

Uploaded by

dsd03832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views27 pages

Python Programs - 250128 - 140055

The document outlines various Python programming tasks, including calculating test averages, creating a Money class with operator overloading, generating Fibonacci numbers, analyzing string similarity, classifying hospital test results, counting examination failures, and maintaining a telephone directory for employees. Each task includes an aim, program code, algorithms, and sample outputs demonstrating the functionality. The programs effectively address their respective objectives while providing error handling and user interaction.

Uploaded by

dsd03832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Question 1: Calculate test average and pass percentage.

Develop a python program to find the best of two test average marks out of three test’s
marks accepted from the user and compute the overall pass percentage for their
placements.
Answer:

AIM:
To develop a python program to find the best of two test average marks out of three
test’s marks accepted from the user and compute the overall pass percentage for their
placements.
PROGRAM:
def calculate_average(marks):
return sum(marks) / len(marks)

def main():
try:
test1 = float(input("Enter test 1 mark: "))
test2 = float(input("Enter test 2 mark: "))
test3 = float(input("Enter test 3 mark: "))

average1 = calculate_average([test1, test2])


average2 = calculate_average([test2, test3])

best_average = max(average1, average2)

passing_grade = 40
if average1 >= passing_grade and average2 >= passing_grade:
passed_students = 2
elif average1 >= passing_grade or average2 >= passing_grade:
passed_students = 1
else:
passed_students = 0

total_students = 2
pass_percentage = (passed_students / total_students) * 100

print(f"Best average: {best_average:.2f}")


print(f"Overall pass percentage: {pass_percentage:.2f}%")

except ValueError:
print("Invalid input. Please enter valid numeric test marks.")

if __name__ == "__main__":
main()

Algorithm:
1. Initialize variables to store the test marks and the best average.
2. Accept three test marks from the user.
3. Calculate the average of the first two test marks.
4. Calculate the average of the last two test marks.
5. Compare the two averages to find the best average.
6. Accept the passing grade (default is 40).
7. Check if both averages are greater than or equal to the passing grade.
8. Compute the overall pass percentage based on the number of students who
passed.
9. Display the best average and overall pass percentage.
Sample Output:
Enter test 1 mark: 65
Enter test 2 mark: 72
Enter test 3 mark: 58
Best average: 70.00
Overall pass percentage: 100.00%

Result:
The program effectively determines the 2 of the highest marks out of 3 given marks and
calculates the average marks and the pass percentage.
Question 2: Money class with Operators

Write a class Money with attributes Rupees and Paise. Overload operators +=, -=, and >=
so that they may be used on two objects. Also write functions so that a desired amount
of money can be either added or subtracted from Money.

Answer:

AIM:
To develop a python program consisting of a class Money with attributes Rupees and
Paise. Overload operators +=, -=, and >= so that they may be used on two objects. Also
write functions so that a desired amount of money can be either added or subtracted
from Money.

PROGRAM:
class Money:
def __init__(self, rupees=0, paise=0):
self.rupees = rupees
self.paise = paise

def __iadd__(self, other):


if isinstance(other, Money):
self.rupees += other.rupees
self.paise += other.paise
return self
else:
raise ValueError("Unsupported operand type")

def __isub__(self, other):


if isinstance(other, Money):
self.rupees -= other.rupees
self.paise -= other.paise
return self
else:
raise ValueError("Unsupported operand type")

def __ge__(self, other):


if isinstance(other, Money):
total_amount_self = self.rupees * 100 + self.paise
total_amount_other = other.rupees * 100 + other.paise
return total_amount_self >= total_amount_other
else:
raise ValueError("Unsupported operand type")

def add_amount(self, rupees, paise):


self.rupees += rupees
self.paise += paise

def subtract_amount(self, rupees, paise):


self.rupees -= rupees
self.paise -= paise

def main():
# Example usage
money1 = Money(100, 50)
money2 = Money(80, 75)

money1 += money2
print(f"Total money after addition: {money1.rupees} Rupees and {money1.paise}
Paise")

money1 -= money2
print(f"Total money after subtraction: {money1.rupees} Rupees and {money1.paise}
Paise")
print(f"Is money1 greater than or equal to money2? {money1 >= money2}")

if __name__ == "__main__":
main()

Algorithm:
1. Create a class called Money with attributes rupees and paise.
2. Define an __init__ method to initialize the attributes.
3. Overload the += operator using the __iadd__ method:
o Add the rupees and paise from another Money object to the current object.
4. Overload the -= operator using the __isub__ method:
o Subtract the rupees and paise from another Money object from the current
object.
5. Overload the >= operator using the __ge__ method:
o Compare the total amount (rupees + paise) of two Money objects.
6. Write functions to add or subtract a desired amount of money:
o Accept the amount to be added or subtracted as input.
o Update the rupees and paise accordingly.

Sample Output:
Total money after addition: 180 Rupees and 125 Paise
Total money after subtraction: 100 Rupees and 50 Paise
Is money1 greater than or equal to money2? True

Result:
The program effectively achieves the goal of handling money amounts (in rupees and
paise) and provides functionality for adding, subtracting, and comparing them.
Question 3: Fibonacci Series using Recurring formula

Define a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error
message if the condition for input value is not followed.

Answer:

AIM:
To define a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error
message if the condition for input value is not followed.

PROGRAM:
def calculate_fibonacci(N):
if N <= 0:
raise ValueError("Input value must be greater than 0")
elif N == 1:
return 0
elif N == 2:
return 1
else:
a, b = 0, 1
for _ in range(2, N):
c=a+b
a, b = b, c
return b

def main():
try:
N = int(input("Enter a positive integer value for N: "))
result = calculate_fibonacci(N)
print(f"The {N}th Fibonacci number is: {result}")
except ValueError:
print("Invalid input. Please enter a valid positive integer.")
if __name__ == "__main__":
main()

Algorithm:
1. Define a function called calculate_fibonacci that takes an integer (N) as input.
2. Validate the input:
o If (N) is less than or equal to 0, raise a ValueError with an appropriate error
message.
3. Initialize variables (a) and (b) with initial values 0 and 1, respectively.
4. Iterate from 2 to (N):
o Calculate the next Fibonacci number as (c = a + b).
o Update (a) and (b) to be the last two Fibonacci numbers: (a = b) and (b = c).
5. Return the value of (b) (which represents the (N)th Fibonacci number).

Sample Output:
Enter a positive integer value for N: 7
The 7th Fibonacci number is: 8

Result:
The program effectively defines a function to compute the (N)th Fibonacci number
using the recursive formula.
Question 4: Calculating String Similarity

Analyze the string similarity between two given strings using Python program.
Sample Output:
Original string:
Python Exercises
Python Exercise

Answer:

AIM:
To analyze the string similarity between two given strings using Python program.

PROGRAM:
import difflib

def calculate_similarity(string1, string2):


sequence_matcher = difflib.SequenceMatcher(None, string1, string2)
return sequence_matcher.ratio()

def main():
string1 = "Python Exercises"
string2 = "Python Exercise"

print("Original strings:")
print(string1)
print(string2)

similarity_ratio = calculate_similarity(string1, string2)


print("\nSimilarity ratio:", similarity_ratio)

if __name__ == "__main__":
main()
Algorithm:
1. Import the difflib module.
2. Define a function called calculate_similarity that takes two strings as input.
3. Create a SequenceMatcher object with the two input strings.
4. Use the ratio() method of the SequenceMatcher to calculate the similarity ratio.
5. Display the original strings and the similarity ratio.

Sample Output:
Original strings:
Python Exercises
Python Exercise

Similarity ratio: 0.956521

Result:
The program effectively defines a function to compute the (N)th Fibonacci number
using the recursive formula.
Question 5: Classify Hospital Test Results as Normal Or Not Normal

A hospital has received a set of lab reports. Totally five tests are conducted in the lab
and the report is prepared in such a way that the 'nth' number correspond to value of test
n. Given are the details of a test made for a patient, write an algorithm and the
subsequent Python program to print if the test result is normal or not normal by referring
to the values in Table 1. Since the value is sensitive, provide a mechanism so that the
values do not get altered.

Name of the Test Minimum Value Maximum Value


Test 1 20 30
Test 2 35.5 40
Test 3 12 15
Test 4 120 150
Test 5 80 120

Answer:

AIM:
The aim of the program is to check if user input values for subsequent tests are a
within the range of values specified in the program.
PROGRAM:
# Step 1: Create a dictionary with normal range values for each test
normal_ranges = {'Test1': {'min': 20, 'max': 30},
'Test2': {'min': 35.5, 'max': 40},
'Test3': {'min': 12, 'max': 15},
'Test4': {'min': 120, 'max': 150},
'Test5': {'min': 80, 'max': 120}}

# Step 2: Ask user to input test name and result


try:
test_name = input("Enter the name of the test (Test1 to Test5): ")
test_result = float(input("Enter the test result: "))

# Step 3: Check if entered test name is within normal ranges


if not (test_name in normal_ranges):
print("Invalid test name. Please enter a valid test name (Test1 to Test5).")
exit()

# Step 4: Retrieve normal range values


min_value = normal_ranges[test_name]['min']
max_value = normal_ranges[test_name]['max']

# Step 5: Compare test result with normal range


if min_value <= test_result <= max_value:
print("Test result is normal.")
else:
print("Test result is not normal.")

except ValueError:
print("Invalid input. Please enter a valid number.")

Algorithm:
1. Create a dictionary called normal_ranges with keys representing test names (e.g.,
‘Test1’, ‘Test2’) and values containing dictionaries with ‘min’ and ‘max’ values for
each test.
2. Prompt the user to input the test name and test result.
3. Validate the user’s input:
o If the test name is not valid (not in the dictionary), print an error message
and exit.
o If the test result is not a valid number, print an error message.
4. Retrieve the normal range values for the specified test.
5. Compare the test result with the normal range:
o If the test result is within the normal range, print “Test result is normal.”
o Otherwise, print “Test result is not normal.”
Sample Output:
Enter the name of the test (Test1 to Test5): Test2
Enter the test result: 38.5
Test result is normal.

Result:
The program effectively determines whether a test result is normal or not based on the
predefined normal ranges for each test. It handles user input errors and provides
informative error messages when necessary.
Question 6: Counting Number of Failures

A University has published the results of the term end examination conducted in April. A
list of failures in physics, mathematics, chemistry, and computer science is available.
Write a program to find the number of failures in the examination. This includes the
count of failures in one or more subjects.

Answer:
AIM:
To write a program to find the number of failures in an examination. This includes the
count of failures in one or more subjects.

PROGRAM:
def main():
num_students = int(input("Enter the number of students: "))

physics_failures = 0
math_failures = 0
chemistry_failures = 0
cs_failures = 0

for _ in range(num_students):
failed_subjects = input("Enter the failed subjects (comma-separated): ").split(", ")

if "physics" in failed_subjects:
physics_failures += 1
if "mathematics" in failed_subjects:
math_failures += 1
if "chemistry" in failed_subjects:
chemistry_failures += 1
if "computer science" in failed_subjects:
cs_failures += 1
total_failures = physics_failures + math_failures + chemistry_failures + cs_failures
print(f"Total number of students who failed in one or more subjects:
{total_failures}")

if __name__ == "__main__":
main()
Algorithm:
1. Initialize variables to store the count of students who failed in each subject
(physics, mathematics, chemistry, and computer science).
2. Accept the number of students from the user.
3. Iterate through each student:
o Prompt the user to input whether the student failed in physics,
mathematics, chemistry, or computer science.
o If the student failed in any subject, increment the corresponding count.
4. Calculate the total count of students who failed in one or more subjects.
5. Display the result.

Sample Output:
Enter the number of students: 3
Enter the failed subjects (comma-separated): physics, mathematics
Enter the failed subjects (comma-separated): chemistry
Enter the failed subjects (comma-separated): computer science
Total number of students who failed in one or more subjects: 3

Result:
The program effectively finds the number of failures in an examination including the
count of failures in one or more subjects.
Question 7: Telephone Directory for Employees

Write a program to maintain a telephone directory of the employees of an organization. If


the employee has more than one number store all the numbers. Write a program to print
the mobile numbers given full or part of the name of the employee. Eg: Given name of the
employee as ‘John’ the program must print phone numbers of ‘John Paul’ and ‘Michel
John’.

Answer:

AIM:
To write a program to print the mobile numbers given full or part of the name of the
employee from a defined telephone directory.

PROGRAM:
def add_employee(directory, name, phone_numbers):
if name in directory:
directory[name].extend(phone_numbers)
else:
directory[name] = phone_numbers

def search_employee(directory, search_name):


for name, phone_numbers in directory.items():
if search_name.lower() in name.lower():
print(f"{name}: {', '.join(phone_numbers)}")

def main():
employee_directory = {}

while True:
print("\n1. Add employee")
print("2. Search employee")
print("3. Exit")
choice = int(input("Enter your choice: "))

if choice == 1:
name = input("Enter employee name: ")
phone_numbers = input("Enter phone numbers (comma-separated): ").split(", ")
add_employee(employee_directory, name, phone_numbers)
elif choice == 2:
search_name = input("Enter full or partial employee name: ")
search_employee(employee_directory, search_name)
elif choice == 3:
break
else:
print("Invalid choice. Please select 1, 2, or 3.")

if __name__ == "__main__":
main()

Algorithm:
1. Create an empty dictionary to store employee names as keys and their phone
numbers (as a list) as values.
2. Define a function called add_employee that accepts the employee name and
phone number(s) as input:
o If the employee name already exists in the dictionary, append the new
phone number(s) to the existing list.
o Otherwise, create a new entry with the employee name and the provided
phone number(s).
3. Define a function called search_employee that accepts a full or partial employee
name as input:
o Iterate through the dictionary keys (employee names).
o Check if the input name is a substring of any employee name.
o If found, print the employee name and their phone number(s).
4. Repeat steps 2 and 3 as needed based on user input.

Sample Output:
1. Add employee
2. Search employee
3. Exit
Enter your choice: 1
Enter employee name: Alice
Enter phone numbers (comma-separated): 123-456-7890, 987-654-3210

1. Add employee
2. Search employee
3. Exit
Enter your choice: 1
Enter employee name: Bob
Enter phone numbers (comma-separated): 555-123-4567, 888-987-6543

1. Add employee
2. Search employee
3. Exit
Enter your choice: 2
Enter full or partial employee name: Al
Alice: 123-456-7890, 987-654-3210

1. Add employee
2. Search employee
3. Exit
Enter your choice: 2
Enter full or partial employee name: Bo
Bob: 555-123-4567, 888-987-6543

1. Add employee
2. Search employee
3. Exit
Enter your choice: 3

Result:
The program effectively creates a telephone directory and finds the number of the person
using their name or their partial name.
Question 8: Average marks using Class

A proctor of our university wants a student to write a program that calculates the average
of marks scored by her wards in CAT1. She has the details such as name, register
number, mark1, mark2 and mark3 of her proctees. The constraint given by the faculty is
that any of the details must not be altered by mistake. Help the student to develop a
Python program.

Answer:

AIM:
To write python program that calculates the average of marks scored by the proctees in
CAT1. The program ensures that none of the details (name, register number, mark1,
mark2, and mark3) are altered.

PROGRAM:
class Proctee:
def __init__(self, name, reg_number, mark1, mark2, mark3):
self.name = name
self.reg_number = reg_number
self.mark1 = mark1
self.mark2 = mark2
self.mark3 = mark3

def calculate_average(self):
return (self.mark1 + self.mark2 + self.mark3) / 3

def main():
name = input("Enter proctee's name: ")
reg_number = input("Enter proctee's register number: ")
mark1 = float(input("Enter mark 1: "))
mark2 = float(input("Enter mark 2: "))
mark3 = float(input("Enter mark 3: "))
proctee = Proctee(name, reg_number, mark1, mark2, mark3)
average = proctee.calculate_average()

print("\nProctee Details:")
print(f"Name: {proctee.name}")
print(f"Register Number: {proctee.reg_number}")
print(f"Average Marks: {average:.2f}")

if __name__ == "__main__":
main()

Algorithm:
1. Create a class called Proctee with attributes for name, register number, and marks
(mark1, mark2, and mark3).
2. Define an __init__ method to initialize the attributes.
3. Define a method called calculate_average that calculates the average of the three
marks.
4. Create an instance of the Proctee class for each proctee.
5. Accept input for the proctee’s details (name, register number, and marks).
6. Display the proctee’s details and the calculated average.
Sample Output:
Enter proctee's name: Alice
Enter proctee's register number: 12345
Enter mark 1: 85
Enter mark 2: 90
Enter mark 3: 88

Proctee Details:
Name: Alice
Register Number: 12345
Average Marks: 87.67

Result:
The program effectively calculates the average of marks scored by the proctees in CAT1.
Question 9: Counting Number of Centums from a CSV File

Consider the following scenario for finding the number of students who secured centum
in mathematics in their examination. A total of 6 lakhs students appeared for the
examinations and their results are generated automatically and updated to the portal
using file.

Answer:

AIM:
To write python program that reads student results from a file and calculates the number
of students who secured centum (100) in mathematics

PROGRAM:
def main():
try:
# Assuming the results are stored in a CSV file named "results.csv"
with open("results.csv", "r") as file:
lines = file.readlines()

centum_math_students = 0
for line in lines:
student_data = line.strip().split(",") # Assuming CSV format:
name,reg_number,math_marks
math_marks = int(student_data[2]) # Index 2 corresponds to mathematics marks
if math_marks == 100:
centum_math_students += 1

print(f"Number of students who secured centum in mathematics:


{centum_math_students}")

except FileNotFoundError:
print("Results file not found. Please ensure the file exists.")
if __name__ == "__main__":
main()

Algorithm:
1. Read the student results from a file (e.g., a CSV file).
2. Initialize a variable to count the number of students who secured centum in
mathematics.
3. Iterate through each student’s result:
o Extract the mathematics marks.
o If the mathematics marks are 100, increment the count.
4. Display the total number of students who secured centum in mathematics.

Sample Output:
Number of students who secured centum in mathematics: 3

Result:
The program effectively reads student results from a CSV file and calculates the number
of students who secured centum (100) in mathematics.
Question 10: River Crossing puzzle using multiple functions

A farmer with a fox, a goose, and a sack of corn needs to cross a river. Now he is on the
east side of the river and wants to go to west side. The farmer has a rowboat, but there is
room for only the farmer and one of his three items. Unfortunately, both the fox and the
goose are hungry. The fox cannot be left alone with the goose, or the fox will eat the
goose. Likewise, the goose cannot be left alone with the sack of corn, or the goose will
eat the corn. Given a sequence of moves find if all the three items fox, goose and corn
are safe. The input sequence indicate the item carried by the farmer along with him in the
boat. ‘F’ – Fox, ‘C’ – Corn, ‘G’ – Goose, N-Nothing. As he is now on the eastern side the
first move is to west and direction alternates for each step.

Answer:

AIM:
To write python program that takes a sequence of moves as input and checks if all three
items remain safe during the entire process.

PROGRAM:
def main():
farmer_position = "east"
fox_position = "east"
goose_position = "east"
corn_position = "east"

moves = input("Enter the sequence of moves (F, C, G, N): ").upper()

for move in moves:


if move == "F":
farmer_position = "west" if farmer_position == "east" else "east"
fox_position = "west" if fox_position == "east" else "east"
elif move == "G":
farmer_position = "west" if farmer_position == "east" else "east"
goose_position = "west" if goose_position == "east" else "east"
elif move == "C":
farmer_position = "west" if farmer_position == "east" else "east"
corn_position = "west" if corn_position == "east" else "east"
elif move == "N":
farmer_position = "west" if farmer_position == "east" else "east"

if (fox_position == goose_position and farmer_position != fox_position) or \


(goose_position == corn_position and farmer_position != goose_position):
print("Unsafe move! The fox would eat the goose or the goose would eat the
corn.")
return

print("All items are safe!")

if __name__ == "__main__":
main()

Algorithm:
1. Initialize the farmer’s position (east side) and the initial positions of the fox,
goose, and corn (all on the east side).
2. Accept the sequence of moves from the user.
3. Iterate through each move:
o Update the farmer’s position based on the move.
o Check if the current state is valid (i.e., no unsafe combinations).
4. Display the final result: whether all three items are safe or not.

Sample Output:
Enter the sequence of moves (F, C, G, N): FCGN
All items are safe!

Result:
The program effectively takes a sequence of moves as input and checks if all three items
remain safe during the entire process.
Question 11: Calculate Funds Required for Setting Up Lab.

A university is setting up a new lab at their premises. Design an algorithm and write
Python code to determine the approximate cost to be spent for setting up the lab. Cost
for setting the lab is sum of cost of computers, cost of furnitures and labour cost. Use
the following formulae for solving the problem.

Answer:

AIM:
To write a python program that calculates the approximate cost for setting up a new lab
based on the cost of computers, furniture, and labor. The program uses the provided
formulae to compute the total cost.

PROGRAM:
def main():
try:
cost_computers = float(input("Enter the cost of computers: "))
cost_furniture = float(input("Enter the cost of furniture: "))
cost_labor = float(input("Enter the labor cost: "))

total_cost = cost_computers + cost_furniture + cost_labor


print(f"Approximate total cost for setting up the lab: ${total_cost:.2f}")

except ValueError:
print("Invalid input. Please enter valid numeric values.")

if __name__ == "__main__":
main()

Algorithm:
1. Accept input for the cost of computers, cost of furniture, and labor cost.
2. Calculate the total cost by summing up the three costs.
3. Display the total cost.
Sample Output:
Enter the cost of computers: 2500
Enter the cost of furniture: 1500
Enter the labor cost: 800

Approximate total cost for setting up the lab: $4800.00

Result:
The program effectively calculates the approximate cost for setting up a new lab based
on the cost of computers, furniture, and labor. The program uses the provided formulae
to compute the total cost.

You might also like