0% found this document useful (0 votes)
2 views

python final

The document contains a series of Python assignments that include tasks such as merging sorted lists, managing footballer goal statistics, copying file contents with line numbers, calculating the HCF of integers, and modeling 2D and 3D points with classes. Each assignment includes a problem statement, Python code implementation, and example outputs. The assignments cover various programming concepts including data structures, exception handling, and object-oriented programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python final

The document contains a series of Python assignments that include tasks such as merging sorted lists, managing footballer goal statistics, copying file contents with line numbers, calculating the HCF of integers, and modeling 2D and 3D points with classes. Each assignment includes a problem statement, Python code implementation, and example outputs. The assignments cover various programming concepts including data structures, exception handling, and object-oriented programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Date:

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

# Merge the two lists by comparing elements


while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1

# Append remaining elements of list1, if any


while i < len(list1):
merged_list.append(list1[i])
i += 1

# Append remaining elements of list2, if any


while j < len(list2):
merged_list.append(list2[j])
j += 1

return merged_list

# Input two lists from the user


list1 = list(map(int, input("Enter the elements of the first list
separated by space: ").split()))
list2 = list(map(int, input("Enter the elements of the second
list separated by space: ").split()))

# Sort both lists


list1.sort()
list2.sort()

# Merge the two sorted lists


sorted_merged_list = merge_sorted_lists(list1, list2)
# Output the sorted merged list
print("The merged sorted list is:", sorted_merged_list)
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 elements of the first list separated by space: 11 15 23
22 34
Enter the elements of the second list separated by space: 4 7 13
25 36
The merged sorted list is: [4, 7, 11, 13, 15, 22, 23, 25, 34, 36]
PS F:\Desktop\5th sem python assignment>
Date:

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,
}

# Sort the dictionary by goals in descending order


sorted_footballers = sorted(footballers_goals.items(),
key=lambda
x: x[1], reverse=True)

# Display the footballer with the highest number of goals


highest_goal_scorer = sorted_footballers[0]
print(f"The footballer who has scored the highest number of
goals is {highest_goal_scorer[0]} with {highest_goal_scorer[1]}
goals.")

# Display the sorted dictionary


print("\nSorted Footballers by Goals (Descending Order):")
for player, goals in sorted_footballers:
print(f"{player}: {goals} goals")
# Run the program
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"
The footballer who has scored the highest number of goals is Pele
with 1279 goals.
Sorted Footballers by Goals (Descending Order):
Pele: 1279 goals
Cristiano Ronaldo: 910 goals
Lionel Messi: 850 goals
Cruyff: 582 goals
Suyarez: 550 goals
Miroslav Klose: 529 goals
Ronaldo Nazário: 481 goals
PS F:\Desktop\5th sem python assignment>
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.

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: ")

# 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/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 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 math.sqrt((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 = point1.add(point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")

# Compute the distance between the points


distance = point1.distance(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/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 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 math.sqrt((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 math.sqrt((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 = point1.add(point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")

# Compute the distance between the points

distance = point1.distance(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/python3.11.exe"
"f:/Desktop/5th sem python assignment/ass.py"
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.
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 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 math.sqrt((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 math.sqrt((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 = point1.add(point2)
print(f"Sum of Point 1 and Point 2: {sum_point}")

# Compute the distance between the points


distance = point1.distance(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/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()

# Reverse the first string and convert the second string


to uppercase
new_string = f"{str1[::-1]} {str2.upper()}"

# 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/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()

# 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/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 push(self, item):


"""Push an item onto the stack."""
self.stack.append(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 = 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")

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()
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.")

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()
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.")

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/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...

You might also like