Write A Program To Find The Factorial of A Give...
Write A Program To Find The Factorial of A Give...
def factorial_recursive(n):
"""
Calculates the factorial of a non-negative integer using recursion.
Args:
n: A non-negative integer.
Returns:
The factorial of n.
Returns 1 if n is 0.
Returns None for negative input.
"""
if n < 0:
return None
elif n == 0:
return 1
else:
return n * factorial_recursive(n - 1)
# Get input from the user
num = int(input("Enter a non-negative integer: "))
# Calculate and print the factorial
result = factorial_recursive(num)
if result is not None:
print(f"The factorial of {num} is {result}")
else:
print("Factorial is not defined for negative numbers.")
3. Write a program to perform all the insertion operations in the singly linked list using
switch case.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
"""Displays the elements of the linked list."""
current = self.head
if current is None:
print("List is empty.")
return
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
def insert_at_beginning(self, data):
"""Inserts a new node at the beginning of the list."""
new_node = Node(data)
new_node.next = self.head
self.head = new_node
print(f"{data} inserted at the beginning.")
def insert_at_end(self, data):
"""Inserts a new node at the end of the list."""
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
print(f"{data} inserted at the end.")
def insert_at_position(self, data, position):
"""Inserts a new node at a specified position."""
if position <= 0:
print("Invalid position. Position should be >= 1.")
return
if position == 1:
self.insert_at_beginning(data)
return
new_node = Node(data)
current = self.head
prev = None
count = 1
while current and count < position:
prev = current
current = current.next
count += 1
if count == position:
new_node.next = current
prev.next = new_node
print(f"{data} inserted at position {position}.")
else:
print(f"Cannot insert at position {position}. Position out of
bounds.")
# Main execution
linked_list = LinkedList()
while True:
print("\nSingly Linked List Insertion Operations:")
print("1. Insert at the beginning")
print("2. Insert at the end")
print("3. Insert at a specific position")
print("4. Display the list")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
data = int(input("Enter data to insert: "))
linked_list.insert_at_beginning(data)
elif choice == '2':
data = int(input("Enter data to insert: "))
linked_list.insert_at_end(data)
elif choice == '3':
data = int(input("Enter data to insert: "))
position = int(input("Enter the position to insert at: "))
linked_list.insert_at_position(data, position)
elif choice == '4':
linked_list.display()
elif choice == '5':
break
else:
print("Invalid choice. Please try again.")
4. Write a program to perform all the deletion operations in the singly linked list using
switch Case.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
"""Displays the elements of the linked list."""
current = self.head
if current is None:
print("List is empty.")
return
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
def delete_from_beginning(self):
"""Deletes the first node from the list."""
if not self.head:
print("List is empty. Cannot delete.")
return
deleted_data = self.head.data
self.head = self.head.next
print(f"{deleted_data} deleted from the beginning.")
def delete_from_end(self):
"""Deletes the last node from the list."""
if not self.head:
print("List is empty. Cannot delete.")
return
if not self.head.next:
deleted_data = self.head.data
self.head = None
print(f"{deleted_data} deleted from the end.")
return
current = self.head
prev = None
while current.next:
prev = current
current = current.next
deleted_data = current.data
prev.next = None
print(f"{deleted_data} deleted from the end.")
def delete_from_position(self, position):
"""Deletes a node from a specified position."""
if not self.head:
print("List is empty. Cannot delete.")
return
if position <= 0:
print("Invalid position. Position should be >= 1.")
return
if position == 1:
self.delete_from_beginning()
return
current = self.head
prev = None
count = 1
while current and count < position:
prev = current
current = current.next
count += 1
if current:
deleted_data = current.data
prev.next = current.next
print(f"{deleted_data} deleted from position {position}.")
else:
print(f"Cannot delete from position {position}. Position out of
bounds.")
# Main execution
linked_list = LinkedList()
while True:
print("\nSingly Linked List Deletion Operations:")
print("1. Delete from the beginning")
print("2. Delete from the end")
print("3. Delete from a specific position")
print("4. Display the list")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
linked_list.delete_from_beginning()
elif choice == '2':
linked_list.delete_from_end()
elif choice == '3':
position = int(input("Enter the position to delete from: "))
linked_list.delete_from_position(position)
elif choice == '4':
linked_list.display()
elif choice == '5':
break
else:
print("Invalid choice. Please try again.")
6. Write a program to insert a node in the beginning in the circular linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def display(self):
"""Displays the elements of the circular linked list."""
if not self.head:
print("List is empty.")
return
current = self.head
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.head:
break
print(f" (Head: {self.head.data})")
def insert_at_beginning(self, data):
"""Inserts a new node at the beginning of the circular linked
list."""
new_node = Node(data)
if not self.head:
self.head = new_node
self.head.next = self.head
else:
temp = self.head
while temp.next != self.head:
temp = temp.next
new_node.next = self.head
temp.next = new_node
self.head = new_node
print(f"{data} inserted at the beginning.")
# Main execution
circular_list = CircularLinkedList()
circular_list.insert_at_beginning(30)
circular_list.insert_at_beginning(20)
circular_list.insert_at_beginning(10)
circular_list.display()
8. Write a program to perform insertion and deletion operation in the queue using static
implementation.
class StaticQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = -1
self.rear = -1
self.size = 0
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.capacity
def enqueue(self, item):
if self.is_full():
print("Queue is full. Cannot enqueue.")
return
if self.is_empty():
self.front = 0
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = item
self.size += 1
print(f"{item} enqueued into the queue.")
def dequeue(self):
if self.is_empty():
print("Queue is empty. Cannot dequeue.")
return None
item = self.queue[self.front]
self.queue[self.front] = None # Optional: Clear the dequeued slot
self.front = (self.front + 1) % self.capacity
self.size -= 1
if self.size == 0:
self.front = self.rear = -1
print(f"{item} dequeued from the queue.")
return item
def peek(self):
if not self.is_empty():
return self.queue[self.front]
else:
print("Queue is empty. Cannot peek.")
return None
def display(self):
if self.is_empty():
print("Queue is empty.")
return
print("Elements in the queue:")
index = self.front
for _ in range(self.size):
print(self.queue[index], end=" ")
index = (index + 1) % self.capacity
print()
# Main execution
capacity = 5
queue = StaticQueue(capacity)
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()
queue.dequeue()
queue.display()
queue.enqueue(40)
queue.enqueue(50)
queue.enqueue(60) # Will show "Queue is full"
queue.display()
9. Write a program to perform insertion and deletion operation in queue using dynamic
implementation.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class DynamicQueue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, item):
new_node = Node(item)
if self.is_empty():
self.front = self.rear = new_node
else:
self.rear.next = new_node
self.rear = new_node
print(f"{item} enqueued into the queue.")
def dequeue(self):
if self.is_empty():
print("Queue is empty. Cannot dequeue.")
return None
item = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
print(f"{item} dequeued from the queue.")
return item
def peek(self):
if not self.is_empty():
return self.front.data
else:
print("Queue is empty. Cannot peek.")
return None
def display(self):
if self.is_empty():
print("Queue is empty.")
return
print("Elements in the queue:")
current = self.front
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Main execution
queue = DynamicQueue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()
queue.dequeue()
queue.display()
queue.enqueue(40)
queue.display()