Write a program which accept informa on about five student and display same
informa on according to ascending order of their name in ?
Ans :- # Define a class to store student informa on
class Student:
def __init__(self, name, age, marks):
[Link] = name
[Link] = age
[Link] = marks
# Accept informa on for 5 students
students = []
for i in range(5):
print(f"Enter details for student {i+1}:")
name = input("Enter Name: ")
age = int(input("Enter Age: "))
marks = float(input("Enter Marks: "))
[Link](Student(name, age, marks))
# Sort the list by student name
[Link](key=lambda student: [Link])
# Display sorted student informa on
print("\nStudent details in ascending order of name:")
for student in students:
print(f"Name: {[Link]}, Age: {[Link]}, Marks: {[Link]}")
This Python program:
1. Collects the name, age, and marks of five students.
2. Stores them in a List<Student>.
3. Sorts the list alphabe cally by student name.
4. Displays the sorted student details.
Write a program to implement stack ?
Ans :- class Stack:
def __init__(self):
[Link] = []
def push(self, value):
[Link](value)
print(f"{value} pushed onto stack.")
def pop(self):
if self.is_empty():
print("Stack is empty.")
return None
return [Link]()
def peek(self):
if self.is_empty():
print("Stack is empty.")
return None
return [Link][-1]
def is_empty(self):
return len([Link]) == 0
# Demonstra on of stack opera ons
if __name__ == "__main__":
stack = Stack()
[Link](10)
[Link](20)
[Link](30)
print("Top element is:", [Link]())
print("Popped element:", [Link]())
print("Popped element:", [Link]())
print("Popped element:", [Link]())
print("Popped element:", [Link]()) # A empt to pop from empty stack
I've updated your document to implement a stack using Python. This version includes
push, pop, peek, and is_empty methods, along with a demonstra on.
Write a program to convert infix expression into pos ix expression?
Ans :- class Stack:
def __init__(self):
[Link] = []
def push(self, value):
[Link](value)
def pop(self):
if self.is_empty():
return None
return [Link]()
def peek(self):
if self.is_empty():
return None
return [Link][-1]
def is_empty(self):
return len([Link]) == 0
def precedence(self, op):
if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
return 0
def infix_to_pos ix(self, expression):
output = []
operator_stack = Stack()
for char in expression:
if [Link](): # Operand
[Link](char)
elif char == '(':
operator_stack.push(char)
elif char == ')':
while not operator_stack.is_empty() and operator_stack.peek() != '(':
[Link](operator_stack.pop())
operator_stack.pop()
else: # Operator
while (not operator_stack.is_empty() and
[Link](operator_stack.peek()) >= [Link](char)):
[Link](operator_stack.pop())
operator_stack.push(char)
while not operator_stack.is_empty():
[Link](operator_stack.pop())
return "".join(output)
# Demonstra on of infix to pos ix conversion
if __name__ == "__main__":
stack = Stack()
expression = "a+b*(c^d-e)" # Example infix expression
print("Pos ix expression:", [Link]fix_to_pos ix(expression))
I've updated your document to include a Python program that converts an infix
expression to a pos ix expression using a stack
Write a program to check balanced parentheses for a given infix expression?
Ans :- class Stack:
def __init__(self):
[Link] = []
def push(self, value):
[Link](value)
def pop(self):
if self.is_empty():
return None
return [Link]()
def is_empty(self):
return len([Link]) == 0
def is_balanced(expression):
stack = Stack()
matching_parentheses = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in '({[':
[Link](char)
elif char in ')}]':
if stack.is_empty() or [Link]() != matching_parentheses[char]:
return False
return stack.is_empty()
# Demonstra on of checking balanced parentheses
if __name__ == "__main__":
expression = input("Enter an infix expression: ")
if is_balanced(expression):
print("The expression has balanced parentheses.")
else:
print("The expression has unbalanced parentheses.")
Write a program to evaluate pos ix expression ?
Ans :- def evaluate_pos ix(expression):
stack = []
operators = {'+', '-', '*', '/'}
for token in [Link]():
if [Link]():
[Link](int(token))
elif token in operators:
operand2 = [Link]()
operand1 = [Link]()
if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2 # True division
[Link](result)
return [Link]()
# Example usage
pos ix_expr = "5 3 2 * + 9 -"
result = evaluate_pos ix(pos ix_expr)
print("Result:", result)
This program uses a stack to evaluate the pos ix expression by itera ng through tokens,
pushing operands onto the stack, and performing opera ons when encountering an
operator.
Write a program to implement queue ?
Ans:- class Queue:
def __init__(self):
[Link] = []
def enqueue(self, item):
[Link](item)
print(f"Enqueued: {item}")
def dequeue(self):
if self.is_empty():
print("Queue is empty!")
return None
return [Link](0)
def is_empty(self):
return len([Link]) == 0
def peek(self):
if self.is_empty():
print("Queue is empty!")
return None
return [Link][0]
def size(self):
return len([Link])
# Example usage
q = Queue()
[Link](10)
[Link](20)
[Link](30)
print("Dequeued:", [Link]())
print("Front of queue:", [Link]())
print("Queue size:", [Link]())
This program implements a basic queue using a list in Python. It includes opera ons like
enqueue, dequeue, checking if the queue is empty, peeking at the front element, and
ge ng the queue size.
Write a program to implement circular queue ?
Ans:- class CircularQueue:
def __init__(self, capacity):
[Link] = capacity
[Link] = [None] * capacity
[Link] = [Link] = -1
def is_full(self):
return ([Link] + 1) % [Link] == [Link]
def is_empty(self):
return [Link] == -1
def enqueue(self, item):
if self.is_full():
print("Queue is full!")
return
if [Link] == -1:
[Link] = 0
[Link] = ([Link] + 1) % [Link]
[Link][[Link]] = item
print(f"Enqueued: {item}")
def dequeue(self):
if self.is_empty():
print("Queue is empty!")
return None
item = [Link][[Link]]
if [Link] == [Link]:
[Link] = [Link] = -1
else:
[Link] = ([Link] + 1) % [Link]
return item
def peek(self):
if self.is_empty():
print("Queue is empty!")
return None
return [Link][[Link]]
def display(self):
if self.is_empty():
print("Queue is empty!")
return
i = [Link]
while True:
print([Link][i], end=" ")
if i == [Link]:
break
i = (i + 1) % [Link]
print()
# Example usage
cq = CircularQueue(5)
[Link](10)
[Link](20)
[Link](30)
[Link](40)
[Link](50)
[Link]()
print("Dequeued:", [Link]())
[Link](60)
[Link]()
This program implements a circular queue using a fixed-size list in Python. It includes
opera ons like enqueue, dequeue, peek, and display while handling wrap-around cases.
Write a program to implement link list with insert, delete, search, view, and delete
func on ?
Ans :- class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def insert(self, data):
new_node = Node(data)
if not [Link]:
[Link] = new_node
else:
temp = [Link]
while [Link]:
temp = [Link]
[Link] = new_node
print(f"Inserted: {data}")
def delete(self, key):
temp = [Link]
if temp and [Link] == key:
[Link] = [Link]
temp = None
print(f"Deleted: {key}")
return
prev = None
while temp and [Link] != key:
prev = temp
temp = [Link]
if not temp:
print("Key not found!")
return
[Link] = [Link]
temp = None
print(f"Deleted: {key}")
def search(self, key):
temp = [Link]
while temp:
if [Link] == key:
print(f"Found: {key}")
return True
temp = [Link]
print("Key not found!")
return False
def view(self):
temp = [Link]
if not temp:
print("List is empty!")
return
while temp:
print([Link], end=" -> ")
temp = [Link]
print("None")
def delete_list(self):
[Link] = None
print("Linked list deleted!")
# Example usage
ll = LinkedList()
[Link](10)
[Link](20)
[Link](30)
[Link]()
[Link](20)
[Link](20)
[Link]()
ll.delete_list()
[Link]()
This program implements a singly linked list in Python with func ons to insert, delete,
search, view, and delete the en re list.
Write a program to implement ordered link list ?
Ans:- class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class OrderedLinkedList:
def __init__(self):
[Link] = None
def insert(self, data):
new_node = Node(data)
if not [Link] or [Link] >= data:
new_node.next = [Link]
[Link] = new_node
else:
temp = [Link]
while [Link] and [Link] < data:
temp = [Link]
new_node.next = [Link]
[Link] = new_node
print(f"Inserted: {data}")
def delete(self, key):
temp = [Link]
if temp and [Link] == key:
[Link] = [Link]
temp = None
print(f"Deleted: {key}")
return
prev = None
while temp and [Link] != key:
prev = temp
temp = [Link]
if not temp:
print("Key not found!")
return
[Link] = [Link]
temp = None
print(f"Deleted: {key}")
def search(self, key):
temp = [Link]
while temp:
if [Link] == key:
print(f"Found: {key}")
return True
temp = [Link]
print("Key not found!")
return False
def view(self):
temp = [Link]
if not temp:
print("List is empty!")
return
while temp:
print([Link], end=" -> ")
temp = [Link]
print("None")
def delete_list(self):
[Link] = None
print("Ordered linked list deleted!")
# Example usage
oll = OrderedLinkedList()
[Link](30)
[Link](10)
[Link](20)
[Link](40)
[Link]()
[Link](20)
[Link](20)
[Link]()
oll.delete_list()
[Link]()
This program implements an ordered linked list in Python, ensuring elements are
inserted in sorted order. It includes func ons to insert, delete, search, view, and delete
the en re list.
Write a program to implement Joseph problem ?
Ans:- def josephus(n, k):
if n == 1:
return 0
else:
return (josephus(n - 1, k) + k) % n
# Wrapper func on to adjust for 1-based index
def josephus_posi on(n, k):
return josephus(n, k) + 1
# Example usage
n = 7 # Number of people
k = 3 # Step count
print("The safe posi on is:", josephus_posi on(n, k))
This program implements the Josephus problem using recursion, determining the safe
posi on in a circle.