0% found this document useful (0 votes)
1 views33 pages

Python Pract

Btech practical file for python

Uploaded by

pvcsvs7tkp
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)
1 views33 pages

Python Pract

Btech practical file for python

Uploaded by

pvcsvs7tkp
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

1.

Create a calculator program using functions for addition, subtraction,


multiplication, and division.
# Function to add two numbers
def add(x, y):
return x + y

# Function to subtract two numbers


def subtract(x, y):
return x - y

# Function to multiply two numbers


def multiply(x, y):
return x * y

# Function to divide two numbers with error handling


def divide(x, y):
if y == 0:
return "Error: Cannot divide by zero."
return x / y

# Display calculator options


def show_menu():
print("Simple Calculator")
print("-----------------")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Exit")

# Main program loop


def calculator():
while True:
show_menu()
choice = input("Enter choice (1/2/3/4/5): ")

if choice == '5':
print("Exiting calculator. Goodbye!")
break

# Get user input for numbers


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter numeric values.\n")
continue

# Perform operation based on user choice


if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
result = divide(num1, num2)
print("Result:", result)
else:
print("Invalid choice. Please select a valid option.")

print() # Print a blank line for spacing

# Run the calculator


calculator()

Output:
Simple Calculator

-----------------

1. Addition (+)

2. Subtraction (-)

3. Multiplication (*)

4. Division (/)

5. Exit

Enter choice (1/2/3/4/5): 1

Enter first number: 5

Enter second number: 3


Result: 8.0
2. Accept a string from the user and perform operations: reverse, check
palindrome, count vowels and consonants.
def analyze_string(s):
# Reverse the string
reversed_str = s[::-1]

# Check for palindrome (ignoring case and spaces)


cleaned = ''.join([Link]() for c in s if [Link]())
is_palindrome = cleaned == cleaned[::-1]

# Count vowels and consonants


vowels = 'aeiou'
vowel_count = 0
consonant_count = 0

for char in [Link]():


if [Link]():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1

# Output results
print(f"Original String: {s}")
print(f"Reversed String: {reversed_str}")
print(f"Is Palindrome: {'Yes' if is_palindrome else 'No'}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

# Accept user input


user_input = input("Enter a string: ")
analyze_string(user_input)

Output:
Enter a string: madam

Original String: madam


Reversed String: madam
Is Palindrome: Yes
Vowels: 2
Consonants: 3
3. Write a recursive function to find factorial and another to compute
Fibonacci series up to n terms.
# Recursive function to find factorial
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

# Recursive function to find nth Fibonacci number


def fibonacci_term(n):
if n <= 1:
return n
return fibonacci_term(n - 1) + fibonacci_term(n - 2)

# Function to generate Fibonacci series up to n terms


def fibonacci_series(n):
series = []
for i in range(n):
[Link](fibonacci_term(i))
return series

# Main program
try:
num = int(input("Enter a positive integer: "))
if num < 0:
print("Please enter a non-negative integer.")
else:
print(f"\nFactorial of {num} is: {factorial(num)}")
print(f"Fibonacci series up to {num} terms: {fibonacci_series(num)}")
except ValueError:
print("Invalid input. Please enter an integer.")
Output:
Enter a positive integer: 23

Factorial of 23 is: 25852016738884976640000


Fibonacci series up to 23 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711]
4. Create a Python program to manage a student record using a dictionary.
Add, delete, update, and search operations.
# Student Record Management System using Dictionary

student_records = {}

def add_student():
roll_no = input("Enter Roll Number: ")
if roll_no in student_records:
print("Student already exists.")
else:
name = input("Enter Name: ")
grade = input("Enter Grade: ")
student_records[roll_no] = {"Name": name, "Grade": grade}
print("Student added successfully.")

def delete_student():
roll_no = input("Enter Roll Number to delete: ")
if roll_no in student_records:
del student_records[roll_no]
print("Student record deleted.")
else:
print("Student not found.")

def update_student():
roll_no = input("Enter Roll Number to update: ")
if roll_no in student_records:
name = input("Enter New Name: ")
grade = input("Enter New Grade: ")
student_records[roll_no] = {"Name": name, "Grade": grade}
print("Student record updated.")
else:
print("Student not found.")

def search_student():
roll_no = input("Enter Roll Number to search: ")
if roll_no in student_records:
print(f"Record found: {student_records[roll_no]}")
else:
print("Student not found.")

def display_all():
if student_records:
print("\nAll Student Records:")
for roll_no, details in student_records.items():
print(f"Roll No: {roll_no}, Name: {details['Name']}, Grade:
{details['Grade']}")
else:
print("No records to display.")

def main():
while True:
print("\n--- Student Record Menu ---")
print("1. Add Student")
print("2. Delete Student")
print("3. Update Student")
print("4. Search Student")
print("5. Display All Students")
print("6. Exit")

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

if choice == '1':
add_student()
elif choice == '2':
delete_student()
elif choice == '3':
update_student()
elif choice == '4':
search_student()
elif choice == '5':
display_all()
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Run the program


main()

Output:
--- Student Record Menu ---
1. Add Student
2. Delete Student
3. Update Student
4. Search Student
5. Display All Students
6. Exit

Enter your choice (1-6): 1


Enter Roll Number: 12
Enter Name: mayank
Enter Grade: 12

Student added successfully.

--- Student Record Menu ---


1. Add Student
2. Delete Student
3. Update Student
4. Search Student
5. Display All Students
6. Exit

Enter your choice (1-6): 6

Exiting the program.


5. Write a program to perform matrix addition, subtraction, and transpose
using nested lists.

def input_matrix(rows, cols):


print(f"Enter the elements row-wise for a {rows}x{cols} matrix:")
matrix = []
for i in range(rows):
row = list(map(int, input(f"Row {i+1}: ").split()))
if len(row) != cols:
print("Incorrect number of columns. Please try again.")
return input_matrix(rows, cols)
[Link](row)
return matrix

def print_matrix(matrix, name="Matrix"):


print(f"\n{name}:")
for row in matrix:
print(" " + " ".join(map(str, row)))

def add_matrices(m1, m2):


return [[m1[i][j] + m2[i][j] for j in range(len(m1[0]))] for i in
range(len(m1))]

def subtract_matrices(m1, m2):


return [[m1[i][j] - m2[i][j] for j in range(len(m1[0]))] for i in
range(len(m1))]

def transpose_matrix(m):
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

# Main Program
try:
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

print("\nMatrix 1:")
matrix1 = input_matrix(rows, cols)

print("\nMatrix 2:")
matrix2 = input_matrix(rows, cols)
added = add_matrices(matrix1, matrix2)
subtracted = subtract_matrices(matrix1, matrix2)
transposed1 = transpose_matrix(matrix1)
transposed2 = transpose_matrix(matrix2)

print_matrix(matrix1, "Matrix 1")


print_matrix(matrix2, "Matrix 2")
print_matrix(added, "Addition (Matrix1 + Matrix2)")
print_matrix(subtracted, "Subtraction (Matrix1 - Matrix2)")
print_matrix(transposed1, "Transpose of Matrix 1")
print_matrix(transposed2, "Transpose of Matrix 2")

except ValueError:
print("Please enter valid integers for dimensions and elements.")

Output:
Enter number of rows: 2
Enter number of columns: 2

Matrix 1:
Enter the elements row-wise for a 2x2 matrix:

Row 1: 2 2
Row 2: 2 2

Matrix 2:
Enter the elements row-wise for a 2x2 matrix:

Row 1: 2 2
Row 2: 2

Incorrect number of columns. Please try again.


Enter the elements row-wise for a 2x2 matrix:

Row 1: 2 2
Row 2: 2 2

Matrix 1:
2 2
2 2
Matrix 2:
2 2
2 2

Addition (Matrix1 + Matrix2):


4 4
4 4

Subtraction (Matrix1 - Matrix2):


0 0
0 0

Transpose of Matrix 1:
2 2
2 2

Transpose of Matrix 2:
2 2
2 2
6. Create a tuple of numbers and find max, min, average, and product using
built-in functions.
# Input: Create a tuple of numbers
input_str = input("Enter numbers separated by spaces: ")
num_tuple = tuple(map(float, input_str.split()))

# Initialize product manually


product = 1
for num in num_tuple:
product *= num

# Calculations using built-in functions


maximum = max(num_tuple)
minimum = min(num_tuple)
average = sum(num_tuple) / len(num_tuple)

# Output
print(f"\nTuple: {num_tuple}")
print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")
print(f"Average: {average}")
print(f"Product: {product}")

Output:
Enter numbers separated by spaces: 1 2 3 4

Tuple: (1.0, 2.0, 3.0, 4.0)


Maximum: 4.0
Minimum: 1.0
Average: 2.5
Product: 24.0
7. Write a Python program to read from a text file, count number of lines,
words, and characters, and display the results.
def analyze_file(file_path):
try:
with open(file_path, 'r') as file:
lines = [Link]()

line_count = len(lines)
word_count = 0
char_count = 0

for line in lines:


word_count += len([Link]())
char_count += len(line)

print(f"\nFile Analysis of '{file_path}':")


print(f"Total Lines: {line_count}")
print(f"Total Words: {word_count}")
print(f"Total Characters (including spaces): {char_count}")

except FileNotFoundError:
print("File not found. Please check the path and try again.")

# Main
file_path = input("Enter the path to the text file: ")
analyze_file(file_path)

Output:
Enter the path to the text file: none

File not found. Please check the path and try again.
8. Create a class BankAccount with attributes and methods for deposit,
withdraw, and balance check. Demonstrate the object creation and method
calls.
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
[Link] = initial_balance

def deposit(self, amount):


if amount > 0:
[Link] += amount
print(f"Deposited ₹{amount}. New balance: ₹{[Link]}")
else:
print("Deposit amount must be positive.")

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient balance.")
elif amount <= 0:
print("Withdrawal amount must be positive.")
else:
[Link] -= amount
print(f"Withdrew ₹{amount}. New balance: ₹{[Link]}")

def check_balance(self):
print(f"Current balance: ₹{[Link]}")

# Main Program
print("Welcome to the Bank Account System")

# User input for account details


account_holder = input("Enter account holder's name: ")
initial_balance = float(input(f"Enter initial balance for {account_holder}
(₹): "))

# Create a bank account object


account = BankAccount(account_holder, initial_balance)

# Display the current balance


account.check_balance()
# Menu for user operations
while True:
print("\nChoose an operation:")
print("1. Deposit money")
print("2. Withdraw money")
print("3. Check balance")
print("4. Exit")

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

if choice == '1':
deposit_amount = float(input("Enter the amount to deposit: ₹"))
[Link](deposit_amount)
elif choice == '2':
withdraw_amount = float(input("Enter the amount to withdraw: ₹"))
[Link](withdraw_amount)
elif choice == '3':
account.check_balance()
elif choice == '4':
print("Thank you for using the Bank Account System. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

Output:
Welcome to the Bank Account System

Enter account holder's name: harsh


Enter initial balance for harsh (₹): 123

Current balance: ₹123.0

Choose an operation:
1. Deposit money
2. Withdraw money
3. Check balance
4. Exit

Enter your choice (1-4): 1


Enter the amount to deposit: ₹ 123
Deposited ₹123.0. New balance: ₹246.0

Choose an operation:
1. Deposit money
2. Withdraw money
3. Check balance
4. Exit

Enter your choice (1-4): 4

Thank you for using the Bank Account System. Goodbye!


9. Implement Bubble Sort, Insertion Sort, and Selection Sort.
# Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] # Swap the elements
swapped = True
if not swapped: # If no two elements were swapped, then the array is
already sorted
break
return arr

# Insertion Sort
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
# Move elements of arr[0..i-1], that are greater than key, to one
position ahead
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr

# Selection Sort
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i] # Swap the found minimum
element with the first element
return arr

# Main Program to demonstrate sorting


if __name__ == "__main__":
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original Array:")
print(arr)

# Bubble Sort
bubble_sorted = [Link]()
bubble_sort(bubble_sorted)
print("\nBubble Sorted Array:")
print(bubble_sorted)

# Insertion Sort
insertion_sorted = [Link]()
insertion_sort(insertion_sorted)
print("\nInsertion Sorted Array:")
print(insertion_sorted)

# Selection Sort
selection_sorted = [Link]()
selection_sort(selection_sorted)
print("\nSelection Sorted Array:")
print(selection_sorted)

Output:
Original Array:
[64, 34, 25, 12, 22, 11, 90]

Bubble Sorted Array:


[11, 12, 22, 25, 34, 64, 90]

Insertion Sorted Array:


[11, 12, 22, 25, 34, 64, 90]

Selection Sorted Array:


[11, 12, 22, 25, 34, 64, 90]
10. Implement Merge Sort and Quick Sort.
# Merge Sort
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Find the middle of the array
left_half = arr[:mid] # Divide the elements into left half
right_half = arr[mid:] # Divide the elements into right half

merge_sort(left_half) # Recursively sort the left half


merge_sort(right_half) # Recursively sort the right half

i = j = k = 0

# Merge the sorted halves


while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

# Check if any element was left in the left half


while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1

# Check if any element was left in the right half


while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1

return arr

# Quick Sort
def quick_sort(arr):
if len(arr) <= 1:
return arr # Base case: if the list has 0 or 1 element, it's already
sorted
pivot = arr[0] # Choose the first element as the pivot
left = [x for x in arr[1:] if x <= pivot] # Elements less than or equal
to pivot
right = [x for x in arr[1:] if x > pivot] # Elements greater than pivot

# Recursively sort the left and right sub-arrays and combine them with
the pivot
return quick_sort(left) + [pivot] + quick_sort(right)

# Main Program to demonstrate sorting


if __name__ == "__main__":
arr = [64, 34, 25, 12, 22, 11, 90]

print("Original Array:")
print(arr)

# Merge Sort
merge_sorted = [Link]()
merge_sort(merge_sorted)
print("\nMerge Sorted Array:")
print(merge_sorted)

# Quick Sort
quick_sorted = [Link]()
quick_sorted = quick_sort(quick_sorted)
print("\nQuick Sorted Array:")
print(quick_sorted)

Output:
Original Array:
[64, 34, 25, 12, 22, 11, 90]

Merge Sorted Array:


[11, 12, 22, 25, 34, 64, 90]

Quick Sorted Array:


[11, 12, 22, 25, 34, 64, 90]
11. Implement a Stack using custom class.
class Stack:
def __init__(self):
# Initialize an empty list to store stack elements
[Link] = []

def is_empty(self):
# Returns True if the stack is empty, False otherwise
return len([Link]) == 0

def push(self, item):


# Add the item to the top of the stack
[Link](item)
print(f"Pushed {item} to stack.")

def pop(self):
# Remove and return the top item of the stack
# Raise an error if the stack is empty
if self.is_empty():
raise IndexError("Error: Cannot pop from an empty stack.")
popped_item = [Link]()
print(f"Popped {popped_item} from stack.")
return popped_item

def peek(self):
# Return the top item without removing it
# Raise an error if the stack is empty
if self.is_empty():
raise IndexError("Error: Cannot peek at an empty stack.")
print(f"Top of stack is {[Link][-1]}")
return [Link][-1]

def size(self):
# Return the number of items in the stack
print(f"Current stack size: {len([Link])}")
return len([Link])

def __str__(self):
# Return a string representation of the stack
return f"Stack(top -> bottom): {[Link][::-1]}"
s = Stack()
try:
[Link](10)
[Link](20)
[Link](30)

[Link]() # Output: Top of stack is 30


[Link]() # Output: Popped 30 from stack
[Link]() # Output: Current stack size: 2
print(s) # Output: Stack(top -> bottom): [20, 10]

[Link]()
[Link]()
[Link]() # Will raise error: Cannot pop from an empty stack
except IndexError as e:
print(e)

Output:
Pushed 10 to stack.
Pushed 20 to stack.
Pushed 30 to stack.
Top of stack is 30
Popped 30 from stack.
Current stack size: 2
Stack(top -> bottom): [20, 10]
Popped 20 from stack.
Popped 10 from stack.
Error: Cannot pop from an empty stack.
12. Implement a Queue using custom class.
class Queue:
def __init__(self):
# Initialize an empty list to hold queue elements
[Link] = []

def is_empty(self):
# Return True if the queue is empty, False otherwise
return len([Link]) == 0

def enqueue(self, item):


# Add an item to the rear of the queue
[Link](item)
print(f"Enqueued {item} to queue.")

def dequeue(self):
# Remove and return the front item of the queue
# Raise an error if the queue is empty
if self.is_empty():
raise IndexError("Error: Cannot dequeue from an empty queue.")
removed_item = [Link](0)
print(f"Dequeued {removed_item} from queue.")
return removed_item

def peek(self):
# Return the front item without removing it
# Raise an error if the queue is empty
if self.is_empty():
raise IndexError("Error: Cannot peek in an empty queue.")
print(f"Front of queue is {[Link][0]}")
return [Link][0]

def size(self):
# Return the number of items in the queue
print(f"Current queue size: {len([Link])}")
return len([Link])

def __str__(self):
# Return a string representation of the queue
return f"Queue(front -> rear): {[Link]}"
q = Queue()
try:
[Link]("A")
[Link]("B")
[Link]("C")

[Link]() # Output: Front of queue is A


[Link]() # Output: Dequeued A from queue
[Link]() # Output: Current queue size: 2
print(q) # Output: Queue(front -> rear): ['B', 'C']

[Link]()
[Link]()
[Link]() # Will raise an error
except IndexError as e:
print(e)

Output:
Enqueued A to queue.
Enqueued B to queue.
Enqueued C to queue.
Front of queue is A
Dequeued A from queue.
Current queue size: 2
Queue(front -> rear): ['B', 'C']
Dequeued B from queue.
Dequeued C from queue.
Error: Cannot dequeue from an empty queue.
13. Implement a Singly Linked List using custom class.
class Node:
def __init__(self, data):
[Link] = data
[Link] = None # Pointer to the next node

class SinglyLinkedList:
def __init__(self):
[Link] = None

def insert_at_end(self, data):


# Insert new node at the end of the list
new_node = Node(data)
if not [Link]:
[Link] = new_node
return
current = [Link]
while [Link]:
current = [Link]
[Link] = new_node

def insert_at_beginning(self, data):


# Insert node at the beginning
new_node = Node(data)
new_node.next = [Link]
[Link] = new_node

def delete_by_value(self, value):


# Delete first node with given value
if not [Link]:
print("List is empty.")
return
if [Link] == value:
[Link] = [Link]
return
current = [Link]
while [Link] and [Link] != value:
current = [Link]
if [Link]:
[Link] = [Link]
else:
print(f"Value {value} not found.")

def display(self):
# Print the linked list
current = [Link]
while current:
print([Link], end=" -> ")
current = [Link]
print("None")
# Create the singly linked list
sll = SinglyLinkedList()
sll.insert_at_end(10)
sll.insert_at_end(20)
sll.insert_at_beginning(5)
[Link]() # Output: 5 -> 10 -> 20 -> None

sll.delete_by_value(10)
[Link]() # Output: 5 -> 20 -> None

sll.delete_by_value(100) # Value 100 not found.

Output:
5 -> 10 -> 20 -> None
5 -> 20 -> None
Value 100 not found.
14. Implement a Doubly Linked using custom class.

class DNode:
def __init__(self, data):
[Link] = data
[Link] = None # Points to previous node
[Link] = None # Points to next node

class DoublyLinkedList:
def __init__(self):
[Link] = None

def insert_at_end(self, data):


new_node = DNode(data)
if not [Link]:
[Link] = new_node
return
current = [Link]
while [Link]:
current = [Link]
[Link] = new_node
new_node.prev = current

def insert_at_beginning(self, data):


new_node = DNode(data)
new_node.next = [Link]
if [Link]:
[Link] = new_node
[Link] = new_node

def delete_by_value(self, value):


if not [Link]:
print("List is empty.")
return
current = [Link]
while current and [Link] != value:
current = [Link]
if not current:
print(f"Value {value} not found.")
return
if [Link]:
[Link] = [Link]
else:
[Link] = [Link]
if [Link]:
[Link] = [Link]

def display_forward(self):
current = [Link]
while current:
print([Link], end=" <-> ")
current = [Link]
print("None")

def display_backward(self):
current = [Link]
while current and [Link]:
current = [Link]
while current:
print([Link], end=" <-> ")
current = [Link]
print("None")
# Create the doubly linked list
dll = DoublyLinkedList()
dll.insert_at_end(1)
dll.insert_at_end(2)
dll.insert_at_beginning(0)
dll.display_forward() # Output: 0 <-> 1 <-> 2 <-> None
dll.display_backward() # Output: 2 <-> 1 <-> 0 <-> None

dll.delete_by_value(1)
dll.display_forward() # Output: 0 <-> 2 <-> None

Output:
0 <-> 1 <-> 2 <-> None
2 <-> 1 <-> 0 <-> None
0 <-> 2 <-> None
15. Implement Binary Search Tree (BST) Operations.
class BSTNode:
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None

class BST:
def __init__(self):
[Link] = None

def insert(self, key):


def _insert(root, key):
if not root:
return BSTNode(key)
if key < [Link]:
[Link] = _insert([Link], key)
elif key > [Link]:
[Link] = _insert([Link], key)
return root
[Link] = _insert([Link], key)

def inorder(self):
# Corrected: Collect keys in a list for clean reuse
def _inorder(node):
if node:
return _inorder([Link]) + [[Link]] +
_inorder([Link])
return []
return _inorder([Link])

def search(self, key):


def _search(root, key):
if not root or [Link] == key:
return root
if key < [Link]:
return _search([Link], key)
return _search([Link], key)
return _search([Link], key)
def delete(self, key):
def _delete(root, key):
if not root:
return None
if key < [Link]:
[Link] = _delete([Link], key)
elif key > [Link]:
[Link] = _delete([Link], key)
else:
# Node with 0 or 1 child
if not [Link]:
return [Link]
elif not [Link]:
return [Link]
# Node with 2 children
temp = self._min_value_node([Link])
[Link] = [Link]
[Link] = _delete([Link], [Link])
return root

[Link] = _delete([Link], key)

def _min_value_node(self, node):


while [Link]:
node = [Link]
return node
# Create and populate the BST
bst = BST()
for num in [50, 30, 70, 20, 40, 60, 80]:
[Link](num)

print("In-order Traversal:", [Link]())


# Output: [20, 30, 40, 50, 60, 70, 80]

# Searching
print("Search for 40:", "Found" if [Link](40) else "Not Found")
print("Search for 100:", "Found" if [Link](100) else "Not Found")

# Deletion
[Link](70)
print("In-order after deleting 70:", [Link]())
# Output: [20, 30, 40, 50, 60, 80]
Output:
In-order Traversal: [20, 30, 40, 50, 60, 70, 80]
Search for 40: Found
Search for 100: Not Found
In-order after deleting 70: [20, 30, 40, 50, 60, 80]
16. Check for Balanced Parentheses using Stack.
def is_balanced(expression):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}

for char in expression:


if char in "([{":
[Link](char)
elif char in ")]}":
if not stack or stack[-1] != pairs[char]:
return False
[Link]()
return len(stack) == 0

# Example usage
expr1 = "{[()]}"
expr2 = "{[(])}"

print(f"{expr1} => {'Balanced' if is_balanced(expr1) else 'Not Balanced'}")


print(f"{expr2} => {'Balanced' if is_balanced(expr2) else 'Not Balanced’}”)

Output:
{[()]} => Balanced
{[(])} => Not Balanced

You might also like