DS Lab Assignment4
DS Lab Assignment4
QUES4.CODE
class Stack:
"""Class to implement Stack as an ADT."""
def __init__(self):
self.stack = []
def pop(self):
"""Pop an item from the stack."""
if not self.is_empty():
return self.stack.pop()
raise IndexError("Pop from empty stack")
def peek(self):
"""Peek at the top item without removing it."""
if not self.is_empty():
return self.stack[-1]
raise IndexError("Peek from empty stack")
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
def size(self):
"""Return the size of the stack."""
return len(self.stack)
def evaluate_postfix(expression):
"""Evaluate a postfix expression using a stack."""
stack = Stack()
for char in expression.split():
if char.isdigit():
stack.push(int(char))
else:
# Pop the top two elements for the operation
b = stack.pop()
a = stack.pop()
if char == '+':
stack.push(a + b)
elif char == '-':
stack.push(a - b)
elif char == '*':
stack.push(a * b)
elif char == '/':
stack.push(a / b)
return stack.pop()
def evaluate_prefix(expression):
"""Evaluate a prefix expression using a stack."""
stack = Stack()
# Iterate in reverse order for prefix
for char in reversed(expression.split()):
if char.isdigit():
stack.push(int(char))
else:
# Pop the top two elements for the operation
a = stack.pop()
b = stack.pop()
if char == '+':
stack.push(a + b)
elif char == '-':
stack.push(a - b)
elif char == '*':
stack.push(a * b)
elif char == '/':
stack.push(a / b)
return stack.pop()
# Example usage
if __name__ == "__main__":
postfix_expr = "5 1 2 + 4 * + 3 -"
print("Postfix Evaluation:", evaluate_postfix(postfix_expr))
OUTPUT
QUES5. CODE
class Queue:
"""Class to implement Queue as an ADT."""
def __init__(self):
self.queue = []
def dequeue(self):
"""Remove and return an item from the front of the queue."""
if not self.is_empty():
return self.queue.pop(0)
raise IndexError("Dequeue from empty queue")
def peek(self):
"""Peek at the front item without removing it."""
if not self.is_empty():
return self.queue[0]
raise IndexError("Peek from empty queue")
def is_empty(self):
"""Check if the queue is empty."""
return len(self.queue) == 0
def size(self):
"""Return the size of the queue."""
return len(self.queue)
def display(self):
"""Display the current state of the queue."""
print("Queue:", self.queue)
# Example usage
if __name__ == "__main__":
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.display()
print("Dequeued:", q.dequeue())
q.display()
print("Peek:", q.peek())
print("Size:", q.size())
OUTPUT