python final
python final
Assignment 9
Problem statement: Write a program to input two lists, sort them and then merge them into third
list in a sorted manner.
Python code:
def merge_sorted_lists(list1, list2):
"""Merge two sorted lists into a single sorted list."""
merged_list = []
i, j = 0, 0
return merged_list
Assignment 10
Problem statement: Define a dictionary to store names of footballers along with the number of
goals they have scored in world cups. Sort the dictionary is descending order of goals. Display
the footballer, who has scored the highest number of goals.
Python code
def main():
# Dictionary storing footballer names as keys and goals as
values
footballers_goals = {
"Suyarez": 550,
"Cristiano Ronaldo": 910,
"Lionel Messi": 850,
"Miroslav Klose": 529,
"Ronaldo Nazário": 481,
"Pele": 1279,
"Cruyff": 582,
}
Assignment 11
Problem statement: Write a program to accept two filenames as command line arguments. Then
copy the contents of one file into another adding line number to each line. Incorporate validation
checks wherever applicable.
Python code:
import sys
import os
def copy_with_line_numbers(src_file, dest_file):
if not os.path.isfile(src_file):
print(f"Error: Source file '{src_file}' not found.")
return
with open(src_file, 'r') as f_in, open(dest_file, 'w') as
f_out:
line_num = 1
for line in f_in:
f_out.write(f"{line_num:04d} {line}")
line_num += 1
if _name_ == "_main_":
if len(sys.argv) != 3:
print("Usage: python script.py <source_file>
<destination_file>")
sys.exit(1)
src_file = sys.argv[1]
dest_file = sys.argv[2]
copy_with_line_numbers(src_file, dest_file)
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
0001 This is the first line.
0002 This is the second line.
0003 This is the third line.
Date:
Assignment 12
Problem statement: Write a program to input a list of integers, numlist[]. Then find the HCF of
the numlist[2] and numlist[8]. Incorporate routines to handle any type of exceptions that may
arise. (Note: Common exceptions in this problem may be NameError, ZeroDivisionError,
IndexError, ValueError etc
Python code:
import math
def get_hcf(a, b):
"""Function to calculate the HCF of two numbers."""
return math.gcd(a, b)
def main():
try:
# Input list of integers
input_string = input("Enter a list of integers separated
by spaces: ")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Enter a list of integers separated by spaces: 67 89 56 78 44 22
66 60 34
The HCF of numlist[2] (56) and numlist[8] (34) is: 2
PS F:\Desktop\5th sem python assignment>
Date:
Assignment 13
Problem statement: Define a class called MyPoint, which models a 2D point with x and y
coordinates. Include the following:
• A constructor that initializes a 2D point.
• A method setXY() to set both x and y.
• A method getXY() which returns the x and y in a list.
• A method to print a point using special member functions.
• A method to add two points.
• A method to compute the distance between this point and another point passed as argument.
• A method to test whether two points are coincident or not.
Write a program to implement the above.
Python code:
import math
class MyPoint:
def __init__(self, x=0, y=0):
"""Constructor to initialize a 2D point with x and y
coordinates."""
self.x = x
self.y = y
def getXY(self):
"""Return the x and y coordinates as a list."""
return [self.x, self.y]
def __str__(self):
"""Return a string representation of the point."""
return f"({self.x}, {self.y})"
def main():
try:
# Input the first point
x1, y1 = map(float, input("Enter coordinates of the first
point (x1 y1): ").split())
point1 = MyPoint(x1, y1)
except ValueError:
print("Error: Invalid input. Please enter numeric values
for coordinates.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Enter coordinates of the first point (x1 y1): 45 12
Enter coordinates of the second point (x2 y2): 3 7
Point 1: (45.0, 12.0)
Point 2: (3.0, 7.0)
Sum of Point 1 and Point 2: (48.0, 19.0)
Distance between Point 1 and Point 2: 42.30
Point 1 and Point 2 are not coincident.
PS F:\Desktop\5th sem python assignment>
Date:
Assignment 14
Problem statement: Derive a class Point3D inherited from the class MyPoint in problem 12.
This class should model a 3D point with x, y and z co-ordinates. Include all the functions in
MyPoint class to perform corresponding operations in a 3D point
Python code:
import math
# Base class for 2D points
class MyPoint:
def __init__(self, x=0, y=0):
"""Constructor to initialize a 2D point with x and y
coordinates."""
self.x = x
self.y = y
def getXY(self):
"""Return the x and y coordinates as a list."""
return [self.x, self.y]
def __str__(self):
"""Return a string representation of the point."""
return f"({self.x}, {self.y})"
self.z = z
def getXYZ(self):
"""Return the x, y, and z coordinates as a list."""
return [self.x, self.y, self.z]
def __str__(self):
"""Return a string representation of the 3D point."""
return f"({self.x}, {self.y}, {self.z})"
# Main program
def main():
try:
# Input the first point
x1, y1, z1 = map(float, input("Enter coordinates of the
first point (x1 y1 z1): ").split())
point1 = Point3D(x1, y1, z1)
# Input the second point
x2, y2, z2 = map(float, input("Enter coordinates of the
second point (x2 y2 z2): ").split())
point2 = Point3D(x2, y2, z2)
distance = point1.distance(point2)
print(f"Distance between Point 1 and Point 2:
{distance:.2f}")
except ValueError:
print("Error: Please enter numeric values for
coordinates.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Output:
Assignment 15
Problem statement: Incorporate the concept of public, private and protected data members in
the above class.
Python code:
import math
# Base class for 2D points
class MyPoint:
def __init__(self, x=0, y=0):
"""Constructor to initialize a 2D point with x and y
coordinates."""
self._x = x # Protected member
self._y = y # Protected member
self.__label = "2D Point" # Private member
def getXY(self):
"""Return the x and y coordinates as a list."""
return [self._x, self._y]
def get_label(self):
"""Access the private label."""
return self.__label
def __str__(self):
"""Return a string representation of the point."""
return f"({self._x}, {self._y})"
def getXYZ(self):
"""Return the x, y, and z coordinates as a list."""
return [self._x, self._y, self.z]
def get_label(self):
"""Access the private label."""
return self.__label
def __str__(self):
"""Return a string representation of the 3D point."""
return f"({self._x}, {self._y}, {self.z})"
# Main program
def main():
try:
# Input the first point
x1, y1, z1 = map(float, input("Enter coordinates of the
first point (x1 y1 z1): ").split())
point1 = Point3D(x1, y1, z1)
print(f"Point 1: {point1}")
print(f"Point 2: {point2}")
print(f"Point 1 label: {point1.get_label()}")
except ValueError:
print("Error: Please enter numeric values for
coordinates.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Enter coordinates of the first point (x1 y1 z1): 5 8 9
Enter coordinates of the second point (x2 y2 z2): 5 8 9
Point 1: (5.0, 8.0, 9.0)
Point 2: (5.0, 8.0, 9.0)
Point 1 label: 3D Point
Sum of Point 1 and Point 2: (10.0, 16.0, 18.0)
Distance between Point 1 and Point 2: 0.00
Point 1 and Point 2 are coincident.
Date:
Assignment 16
Problem statement: Write a program to input two strings and print a new string where the first
string is reversed, and the second string is converted to upper case. Example input: “pets“,
“party”, output: “step PARTY”
Python code:
def main():
try:
# Input two strings from the user
str1 = input("Enter the first string: ").strip()
str2 = input("Enter the second string: ").strip()
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Enter the first string: Hello
Enter the second string: World
Output: olleH WORLD
Date:
Assignment 17
Problem statement: Write a program that initializes a list of words, and then join all the words
in the odd and even indices to form two strings.
Python code:
def main():
try:
# Initialize a list of words
words = input("Enter a list of words separated by spaces:
").strip().split()
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Enter a list of words separated by spaces: irat Kohli is an
Indian cricketer
known for his aggressive batting, leadership, and consistency.
Words at even indices: irat is Indian known his batting, and
Words at odd indices: Kohli an cricketer for aggressive
leadership,
consistency.
Date:
Assignment 18
Problem statement: Write a program to simulate stack and queue using lists
Python code:
class Stack:
def __init__(self):
"""Initialize an empty stack."""
self.stack = []
def pop(self):
"""Pop an item from the stack."""
if self.is_empty():
print("Stack is empty. Cannot pop.")
else:
item = self.stack.pop()
print(f"Item '{item}' popped from the stack.")
return item
def peek(self):
"""Return the top item without popping it."""
if self.is_empty():
print("Stack is empty.")
else:
print(f"Top item is: '{self.stack[-1]}'")
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
def display(self):
"""Display all items in the stack."""
print(f"Current stack: {self.stack}")
class Queue:
def __init__(self):
"""Initialize an empty queue."""
self.queue = []
def enqueue(self, item):
"""Add an item to the end of the queue."""
self.queue.append(item)
print(f"Item '{item}' enqueued to the queue.")
def dequeue(self):
"""Remove an item from the front of the queue."""
if self.is_empty():
print("Queue is empty. Cannot dequeue.")
else:
item = self.queue.pop(0)
print(f"Item '{item}' dequeued from the queue.")
return item
def peek(self):
"""Return the front item without dequeuing it."""
if self.is_empty():
print("Queue is empty.")
else:
print(f"Front item is: '{self.queue[0]}'")
def is_empty(self):
"""Check if the queue is empty."""
return len(self.queue) == 0
def display(self):
"""Display all items in the queue."""
print(f"Current queue: {self.queue}")
def main():
stack = Stack()
queue = Queue()
while True:
print("\nMenu:")
print("1. Stack Operations")
print("2. Queue Operations")
print("3. Exit")
choice = input("Choose an operation (1/2/3): ").strip()
if choice == '1':
# Stack operations
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Back to Main Menu")
if stack_choice == '1':
item = input("Enter item to push onto the
stack: ").strip()
stack.push(item)
elif stack_choice == '2':
stack.pop()
elif stack_choice == '3':
stack.peek()
elif stack_choice == '4':
stack.display()
elif stack_choice == '5':
break
else:
print("Invalid choice. Please try again.")
if queue_choice == '1':
item = input("Enter item to enqueue to the
queue: ").strip()
queue.enqueue(item)
elif queue_choice == '2':
queue.dequeue()
elif queue_choice == '3':
queue.peek()
elif queue_choice == '4':
queue.display()
elif queue_choice == '5':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
PS F:\Desktop\5th sem python assignment> & "C:/Users/Arya
Roy/AppData/Local/Microsoft/WindowsApps/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
Menu:
1. Stack Operations
2. Queue Operations
3. Exit
Choose an operation (1/2/3): 1
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display Stack
5. Back to Main Menu
Choose an operation (1/2/3/4/5): 1
Enter item to push onto the stack: INDIA
Item 'INDIA' pushed onto the stack.
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display Stack
5. Back to Main Menu
Choose an operation (1/2/3/4/5): 4
Current stack: ['INDIA']
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display Stack
5. Back to Main Menu
Choose an operation (1/2/3/4/5): 5
Menu:
1. Stack Operations
2. Queue Operations
3. Exit
Choose an operation (1/2/3): 3
Exiting program...