0% found this document useful (0 votes)
3 views12 pages

Write A Program To Find The Factorial of A Give...

The document contains multiple Python programs demonstrating various data structures and algorithms, including recursion for factorial and Fibonacci calculations, singly linked list operations (insertion, deletion, and traversal), circular linked list insertion, stack operations (push and pop), queue operations (both static and dynamic implementations), and evaluating a postfix expression. Each program is structured with appropriate class definitions and methods to perform the specified operations. The document serves as a comprehensive guide for implementing fundamental data structures and algorithms in Python.
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)
3 views12 pages

Write A Program To Find The Factorial of A Give...

The document contains multiple Python programs demonstrating various data structures and algorithms, including recursion for factorial and Fibonacci calculations, singly linked list operations (insertion, deletion, and traversal), circular linked list insertion, stack operations (push and pop), queue operations (both static and dynamic implementations), and evaluating a postfix expression. Each program is structured with appropriate class definitions and methods to perform the specified operations. The document serves as a comprehensive guide for implementing fundamental data structures and algorithms in Python.
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
You are on page 1/ 12

1. Write a program to find the factorial of a given number using recursion.

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

2. Write a program to print Fibonacci series using recursion.


def fibonacci_recursive(n):​
"""​
Calculates the nth Fibonacci number using recursion.​

Args:​
n: A non-negative integer representing the position in the
Fibonacci series.​

Returns:​
The nth Fibonacci number.​
Returns None for negative input.​
"""​
if n < 0:​
return None​
elif n <= 1:​
return n​
else:​
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)​

# Get input for the number of terms in the Fibonacci series​
num_terms = int(input("Enter the number of terms for the Fibonacci
series: "))​

# Print the Fibonacci series​
if num_terms > 0:​
print("Fibonacci Series:")​
for i in range(num_terms):​
print(fibonacci_recursive(i), end=" ")​
print()​
else:​
print("Please enter a positive number of terms.")​

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

5. Write a program to traverse all the nodes in singly linked list.


class Node:​
def __init__(self, data):​
self.data = data​
self.next = None​

class LinkedList:​
def __init__(self):​
self.head = None​

def insert_at_end(self, data):​
"""Helper function to insert at the end for demonstration."""​
new_node = Node(data)​
if not self.head:​
self.head = new_node​
return​
current = self.head​
while current.next:​
current = current.next​
current.next = new_node​

def traverse_list(self):​
"""Traverses and prints all nodes in the linked list."""​
current = self.head​
if current is None:​
print("The list is empty.")​
return​
print("Elements in the linked list:")​
while current:​
print(current.data, end=" -> ")​
current = current.next​
print("None")​

# Main execution​
linked_list = LinkedList()​
linked_list.insert_at_end(10)​
linked_list.insert_at_end(20)​
linked_list.insert_at_end(30)​
linked_list.traverse_list()​

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()​

7. Write a program to perform push and pop operation in the stack.


class Stack:​
def __init__(self):​
self.items = []​

def is_empty(self):​
return not self.items​

def push(self, item):​
self.items.append(item)​
print(f"{item} pushed onto the stack.")​

def pop(self):​
if not self.is_empty():​
return self.items.pop()​
else:​
print("Stack is empty. Cannot pop.")​
return None​

def peek(self):​
if not self.is_empty():​
return self.items[-1]​
else:​
print("Stack is empty. Cannot peek.")​
return None​

def size(self):​
return len(self.items)​

# Main execution​
stack = Stack()​
stack.push(10)​
stack.push(20)​
stack.push(30)​

print(f"Top element: {stack.peek()}")​
print(f"Size of stack: {stack.size()}")​

popped_item = stack.pop()​
if popped_item is not None:​
print(f"{popped_item} popped from the stack.")​

print(f"Size of stack after pop: {stack.size()}")​

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()​

10. Write a program to evaluate a postfix expression.


def evaluate_postfix(expression):​
"""​
Evaluates a postfix expression.​

Args:​
expression:​

You might also like