0% found this document useful (0 votes)
19 views16 pages

Practical No.6

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

Practical No.6

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

a

Practical No.6

6.Write a program to implement tower of Hanoi.

# def tower_of_hanoi(n, source, target, auxiliary):


Base case: If there is only one disk, move it from source to target if n
== 1:

print(f"Move disk 1 from {source} to {target}") return

# Move n-1 disks from source to auxiliary, so they are out of the way
tower_of_hanoi(n - 1, source, auxiliary, target) # Move the nth disk
from source to target print(f"Move disk {n} from {source} to {target}")

# Move the n-1 disks from auxiliary to target tower_of_hanoi(n -


1, auxiliary, target, source)

# Example usage n = 3 #
Number of disks

tower_of_hanoi(n, 'A', 'C', 'B')

Output

Move disk 1 from A to C


Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A Move
disk 2 from B to C

Move disk 1 from A to C


a

Practical No.7

7. Write a Program to store student roll number and marks using


dictionary. Implements following functions
Add a record, delete, update marks, search a roll number and display
marks, sort the records in ascending and descending order, display
student information with highest marks. Implement a menu driven
program.

# Function to add a student's roll number and marks to the


dictionary def add_record(students): roll_number = input("Enter
the roll number: ") if roll_number in students:

print(f"Roll number {roll_number} already exists. Try updating the


marks instead.") else:

marks = float(input(f"Enter the marks for roll number {roll_number}:


")) students[roll_number] = marks print(f"Student with roll number
{roll_number} added successfully!\n")

# Function to delete a student record by roll number def


delete_record(students): roll_number = input("Enter the roll number to
delete: ") if roll_number in students: del students[roll_number]
print(f"Record with roll number {roll_number} deleted successfully.\n")
else: print(f"No record found for roll number {roll_number}.\n")

# Function to update marks of an existing student def


update_marks(students): roll_number = input("Enter the
roll number to update: ") if roll_number in students:
new_marks = float(input(f"Enter the new marks for roll number
{roll_number}: ")) students[roll_number] = new_marks print(f"Marks for
roll number {roll_number} updated successfully.\n") else: print(f"No
record found for roll number {roll_number}.\n")
a

# Function to search a roll number and display marks


def search_roll_number(students):

roll_number = input("Enter the roll number to search: ")


if roll_number in students:

print(f"Marks for roll number {roll_number}: {students[roll_number]}\


n") else: print(f"No record found for roll number {roll_number}.\n")

# Function to sort and display records in ascending order of marks


def sort_ascending(students):

sorted_students = sorted(students.items(), key=lambda x:


x[1]) print("\nSorted Records (Ascending):") for
roll_number, marks in sorted_students:

print(f"Roll Number: {roll_number}, Marks: {marks}")


print()

# Function to sort and display records in descending order of marks


def sort_descending(students):

sorted_students = sorted(students.items(), key=lambda x: x[1],


reverse=True) print("\nSorted Records (Descending):") for roll_number,
marks in sorted_students:
print(f"Roll Number: {roll_number}, Marks: {marks}")
print()

# Function to display the student with the highest marks


def highest_marks(students):

if students:
a

highest_student = max(students, key=students.get)


print(f"The student with the highest marks is Roll Number:
{highest_student} with marks: {students[highest_student]}\
n") else: print("No records available to find the highest
marks.\n")

# Function to display all students and their marks


def display_students(students):

if students:
print("\nStudent Information:") for
roll_number, marks in students.items():

print(f"Roll Number: {roll_number}, Marks: {marks}")


print()

else: print("No student records


available.\n")

# Main function to implement the menu-driven program


def main(): students = {} # Dictionary to store roll number
and marks while True:

print("Menu:") print("1. Add a


Student Record") print("2.
Delete a Student Record")
print("3. Update Marks")
print("4. Search a Roll Number
and Display Marks") print("5.
Sort Records in Ascending
Order of Marks") print("6. Sort
Records in Descending Order
a

of Marks") print("7. Display


Student with Highest Marks")
print("8. Display All Student
Information") print("9. Exit")

choice = input("Enter your choice (1-9): ")

if choice == '1':
add_record(students)

elif choice == '2':


delete_record(students)

elif choice == '3':


update_marks(students)

elif choice == '4':


search_roll_number(students)

elif choice == '5':


sort_ascending(students)

elif choice == '6':


sort_descending(students)

elif choice == '7':


highest_marks(students)

elif choice == '8':


display_students(students)
elif choice == '9':
print("Exiting the program.") break else:
print("Invalid choice! Please select a valid option.\n")
a

# Run the main function if


__name__ == "__main__":
main()

output
Menu:
1. Add a Student Record
2. Delete a Student Record
3. Update Marks
4. Search a Roll Number and Display Marks
5. Sort Records in Ascending Order of Marks
6. Sort Records in Descending Order of Marks
7. Display Student with Highest Marks
8. Display All Student Information
9. Exit
Enter your choice (1-9): 4 Enter
the roll number to search: 6

No record found for roll number 6.

Practical No.8

8.Write a Program to implement function decorator to display cube of a


number.
a

#Python Program to Find Cube of a Number

num = int(input("Enter an integer: "))

#Calculating cube

cube = num * num * num

# Displaying output

print("Cube of {0} is {1}".format(num, cube))

OUTPUT:

Enter an integer: 10

Cube of 10 is 1000

Practical No 9

9. Write a program to implement generator function to display square of


number form 1 to 10 in python.
a

# Step 1: Define the generator function


def square_generator():

for num in range(1, 11): # Numbers from 1 to 10


yield num ** 2 # Yield the square of the number

# Step 2: Use the generator


squares = square_generator()

# Step 3: Display the squares


for square in squares:
print(square)

Output
1
4
9
16
25
36
49
64
81
100

Practical No 10

10. write a program to validate email id, password, url and mobile using
regular expression.
a

import re

def validate_email(email):

# Regex for validating an Email

email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

return re.match(email_pattern, email) is not None

def validate_password(password):

#Regex for validating a Password

# At least 8 characters, at least one uppercase letter, one lowercase letter, one
digit and one special character

password_pattern = r'^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\
d@$!%?&]{8,}$'

return re.match(password_pattern, password) is not None

def validate_url(url):

# Regex for validating a URL


url_pattern = r'^(http:///https://|ftp://)?(www\.)?[a-zA-Z0-9-]+\.[a-zA-

Z]{2,)(/[a-zA-Z0-9-?&=]*)?$'

return re.match(url_pattern, url) is not None

def validate_mobile(mobile):

#Regex for validating a Mobile Number (10 digits, starting with 7, 8, or 9)

mobile_pattern = r'^[789]\d{9}$'
a

return re.match(mobile_pattern, mobile) is not None

print("Email Valid:", validate_email(email))

print("Password Valid:", validate_password(password))

print("URL Valid:", validate_url(url))

print("Mobile Valid:", validate_mobile(mobile))

OUTPUT:

email = "[email protected]"

password = "Password123!"

url = "https://www.example.com"

mobile = "9421866392"

Practical No .14

14. Write a peogram to find sum and multiplication of two matrices


implement using list in python.
a

#Program to multiply two matrices using nested loops.

# 3 * 3 matrix

X=[ [12, 7, 3] ,

[4,5,6],

[7, 8, 9] ]

3 * 4 matrix

Y=[ [5, 8, 1, 2] ,

[6,7,3,0], [4, 5, 9, 1] ]

# result is 3 * 4

result =[ [0, 0, 0, 0] ,

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):

# iterate through columns of Y


for j in range(len(Y[0])):

#iterate through rows of Y


for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]


for r in result:

print(r)
a

OUTPUT:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

Practical No .15

15. write a program to implement multithreading


a

import threading
import time

# Function to simulate a task that takes some time


def print_numbers():
for i in range(5):
print(i)
time.sleep(1)

# Function to simulate another task


def print_letters():
for letter in 'ABCDE':
print(letter)
time.sleep(1)

# Main function to create and start threads


def main():
# Create two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

# Start the threads


thread1.start()
thread2.start()

# Wait for both threads to finish


thread1.join()
thread2.join()

print("Both tasks are complete.")

# Entry point
if __name__ == "__main__":
main()

Output:
0
A
1
a

B
2
C
3
D
4
E
Both tasks are complete.
a

You might also like