Date:
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.
</code>
import sys
import os
def copy_with_line_numbers(src_file, dest_file):
if not [Link](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([Link]) != 3:
print("Usage: python [Link] <source_file>
<destination_file>")
[Link](1)
src_file = [Link][1]
dest_file = [Link][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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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
</code>
import math
def get_hcf(a, b):
"""Function to calculate the HCF of two numbers."""
return [Link](a, b)
def main():
try:
# Input list of integers
input_string = input("Enter a list of integers separated
by spaces: ")
# Convert the input string to a list of integers
numlist = list(map(int, input_string.split()))
# Check if the list has at least 9 elements
if len(numlist) <= 8:
raise IndexError("The list must contain at least 9
integers.")
# Extract numlist[2] and numlist[8]
num1 = numlist[2]
num2 = numlist[8]
# Check if any number is zero to avoid ZeroDivisionError
if num1 == 0 or num2 == 0:
raise ZeroDivisionError("Cannot calculate HCF when
one of the numbers is zero.")
# Calculate the HCF
hcf = get_hcf(num1, num2)
print(f"The HCF of numlist[2] ({num1}) and numlist[8]
({num2}) is: {hcf}")
except ValueError:
print("Error: Please enter a valid list of integers.")
except IndexError as e:
print(f"Error: {e}")
except ZeroDivisionError as e:
print(f"Error: {e}")
except NameError:
print("Error: Undefined variable encountered.")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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.
</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 setXY(self, x, y):
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 add(self, other_point):
"""Add two points (vector addition)."""
return MyPoint(self.x + other_point.x, self.y +
other_point.y)
def distance(self, other_point):
"""Compute the distance between this point and another
point."""
return [Link]((self.x - other_point.x) ** 2 + (self.y
- other_point.y) ** 2)
def is_coincident(self, other_point):
"""Check if two points are coincident."""
return self.x == other_point.x and self.y ==
other_point.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)
# Input the second point
x2, y2 = map(float, input("Enter coordinates of the
second point (x2 y2): ").split())
point2 = MyPoint(x2, y2)
# Print the points
print(f"Point 1: {point1}")
print(f"Point 2: {point2}")
# Add the two points
sum_point = [Link](point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")
# Compute the distance between the points
distance = [Link](point2)
print(f"Distance between Point 1 and Point 2:
{distance:.2f}")
# Check if the points are coincident
if point1.is_coincident(point2):
print("Point 1 and Point 2 are coincident.")
else:
print("Point 1 and Point 2 are not coincident.")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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
</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 setXY(self, x, y):
"""Set the x and y coordinates of the point."""
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 add(self, other_point):
"""Add two points (vector addition)."""
return MyPoint(self.x + other_point.x, self.y +
other_point.y)
def distance(self, other_point):
"""Compute the distance between this point and another
point."""
return [Link]((self.x - other_point.x) ** 2 + (self.y
- other_point.y) ** 2)
def is_coincident(self, other_point):
"""Check if two points are coincident."""
return self.x == other_point.x and self.y ==
other_point.y
# Derived class for 3D points
class Point3D(MyPoint):
def __init__(self, x=0, y=0, z=0):
"""Constructor to initialize a 3D point with x, y, and z
coordinates."""
super().__init__(x, y)
self.z = z
def setXYZ(self, x, y, z):
"""Set the x, y, and z coordinates of the point."""
self.x = x
self.y = 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})"
def add(self, other_point):
"""Add two 3D points (vector addition)."""
return Point3D(self.x + other_point.x, self.y +
other_point.y, self.z + other_point.z)
def distance(self, other_point):
"""Compute the distance between this 3D point and another
3D point."""
return [Link]((self.x - other_point.x) ** 2 + (self.y
- other_point.y) ** 2 + (self.z - other_point.z) **2)
def is_coincident(self, other_point):
"""Check if two 3D points are coincident."""
return self.x == other_point.x and self.y ==
other_point.y and self.z == other_point.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)
# Print the points
print(f"Point 1: {point1}")
print(f"Point 2: {point2}")
# Add the two points
sum_point = [Link](point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")
# Compute the distance between the points
distance = [Link](point2)
print(f"Distance between Point 1 and Point 2:
{distance:.2f}")
# Check if the points are coincident
if point1.is_coincident(point2):
print("Point 1 and Point 2 are coincident.")
else:
print("Point 1 and Point 2 are not coincident.")
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/[Link]" "f:/Desktop/5th sem python
assignment/[Link]"
Enter coordinates of the first point (x1 y1 z1): 7 9 4
Enter coordinates of the second point (x2 y2 z2): 8 5 1
Point 1: (7.0, 9.0, 4.0)
Point 2: (8.0, 5.0, 1.0)
Sum of Point 1 and Point 2: (15.0, 14.0, 5.0)
Distance between Point 1 and Point 2: 5.10
Point 1 and Point 2 are not coincident.
PS F:\Desktop\5th sem python assignment>
Date:
Assignment 15
Problem statement: Incorporate the concept of public, private and protected data members in
the above class.
</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 setXY(self, x, y):
"""Set the x and y coordinates of the point."""
self._x = x
self._y = y
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 add(self, other_point):
"""Add two points (vector addition)."""
return MyPoint(self._x + other_point._x, self._y +
other_point._y)
def distance(self, other_point):
"""Compute the distance between this point and another
point."""
return [Link]((self._x - other_point._x) ** 2 +
(self._y - other_point._y) ** 2)
def is_coincident(self, other_point):
"""Check if two points are coincident."""
return self._x == other_point._x and self._y ==
other_point._y
# Derived class for 3D points
class Point3D(MyPoint):
def __init__(self, x=0, y=0, z=0):
"""Constructor to initialize a 3D point with x, y, and z
coordinates."""
super().__init__(x, y)
self.z = z # Public member
self.__label = "3D Point" # Private member
def setXYZ(self, x, y, z):
"""Set the x, y, and z coordinates of the point."""
self._x = x
self._y = 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 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})"
def add(self, other_point):
"""Add two 3D points (vector addition)."""
return Point3D(self._x + other_point._x, self._y +
other_point._y, self.z + other_point.z)
def distance(self, other_point):
"""Compute the distance between this 3D point and another
3D point."""
return [Link]((self._x - other_point._x) ** 2 +
(self._y - other_point._y) ** 2 + (self.z -
other_point.z) ** 2)
def is_coincident(self, other_point):
"""Check if two 3D points are coincident."""
return self._x == other_point._x and self._y ==
other_point._y and self.z == other_point.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)
# Print the points
print(f"Point 1: {point1}")
print(f"Point 2: {point2}")
print(f"Point 1 label: {point1.get_label()}")
# Add the two points
sum_point = [Link](point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")
# Compute the distance between the points
distance = [Link](point2)
print(f"Distance between Point 1 and Point 2:
{distance:.2f}")
# Check if the points are coincident
if point1.is_coincident(point2):
print("Point 1 and Point 2 are coincident.")
else:
print("Point 1 and Point 2 are not coincident.")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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”
</code>
def main():
try:
# Input two strings from the user
str1 = input("Enter the first string: ").strip()
str2 = input("Enter the second string: ").strip()
# Reverse the first string and convert the second string
to uppercase
new_string = f"{str1[::-1]} {[Link]()}"
# Output the result
print(f"Output: {new_string}")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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.
</code>
def main():
try:
# Initialize a list of words
words = input("Enter a list of words separated by spaces:
").strip().split()
# Separate words at odd and even indices
even_indices_words = words[::2] # Words at even indices
odd_indices_words = words[1::2] # Words at odd indices
# Join the words into two strings
even_string = " ".join(even_indices_words)
odd_string = " ".join(odd_indices_words)
# Output the results
print(f"Words at even indices: {even_string}")
print(f"Words at odd indices: {odd_string}")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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
</code>
class Stack:
def __init__(self):
"""Initialize an empty stack."""
[Link] = []
def push(self, item):
"""Push an item onto the stack."""
[Link](item)
print(f"Item '{item}' pushed onto the stack.")
def pop(self):
"""Pop an item from the stack."""
if self.is_empty():
print("Stack is empty. Cannot pop.")
else:
item = [Link]()
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: '{[Link][-1]}'")
def is_empty(self):
"""Check if the stack is empty."""
return len([Link]) == 0
def display(self):
"""Display all items in the stack."""
print(f"Current stack: {[Link]}")
class Queue:
def __init__(self):
"""Initialize an empty queue."""
[Link] = []
def enqueue(self, item):
"""Add an item to the end of the queue."""
[Link](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 = [Link](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: '{[Link][0]}'")
def is_empty(self):
"""Check if the queue is empty."""
return len([Link]) == 0
def display(self):
"""Display all items in the queue."""
print(f"Current queue: {[Link]}")
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")
stack_choice = input("Choose an operation
(1/2/3/4/5): ").strip()
if stack_choice == '1':
item = input("Enter item to push onto the
stack: ").strip()
[Link](item)
elif stack_choice == '2':
[Link]()
elif stack_choice == '3':
[Link]()
elif stack_choice == '4':
[Link]()
elif stack_choice == '5':
break
else:
print("Invalid choice. Please try again.")
elif choice == '2':
# Queue operations
while True:
print("\nQueue Operations:")
print("1. Enqueue")
print("2. Dequeue")
print("3. Peek")
print("4. Display Queue")
print("5. Back to Main Menu")
queue_choice = input("Choose an operation
(1/2/3/4/5): ").strip()
if queue_choice == '1':
item = input("Enter item to enqueue to the
queue: ").strip()
[Link](item)
elif queue_choice == '2':
[Link]()
elif queue_choice == '3':
[Link]()
elif queue_choice == '4':
[Link]()
elif queue_choice == '5':
break
else:
print("Invalid choice. Please try again.")
elif choice == '3':
print("Exiting program...")
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/[Link]"
"f:/Desktop/5th sem python assignment/[Link]"
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...