Thanks to visit codestin.com
Credit goes to www.scribd.com

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

ADS Lab Assignment 2

The document outlines a lab assignment on data structures, specifically focusing on stack, infix to postfix, postfix to infix, infix to prefix, and prefix to infix conversions. It includes Python code implementations for each data structure and conversion method, along with example outputs demonstrating their functionality. Additionally, it provides a brief overview of queue operations such as enqueue, dequeue, and checking size and emptiness.

Uploaded by

Shivangi Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

ADS Lab Assignment 2

The document outlines a lab assignment on data structures, specifically focusing on stack, infix to postfix, postfix to infix, infix to prefix, and prefix to infix conversions. It includes Python code implementations for each data structure and conversion method, along with example outputs demonstrating their functionality. Additionally, it provides a brief overview of queue operations such as enqueue, dequeue, and checking size and emptiness.

Uploaded by

Shivangi Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

ADS Lab Assignment 2

Submitted by: Nancy (M.Tech CE)

Stack Implementation
class Stack:
def init (self):
self.stack = []

def push(self, val):


self.stack.append(val)
print(f"{val} pushed onto stack")

def pop(self):
if not self.stack:
print("Stack Underflow (nothing to pop)")
else:
print(f"{self.stack.pop()} popped from stack")

def display(self):
if not self.stack:
print("Stack is Empty")
else:
print("Stack (top → bottom):", self.stack[::-1])

# Driver code
if name == " main ":
s = Stack()

while True:
print("\n--- Stack Menu ---")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")

choice = int(input("Enter choice: "))

if choice == 1:
val = int(input("Enter value to push: "))
s.push(val)
elif choice == 2:
s.pop()
elif choice == 3:
s.display()
elif choice ==
4:
print("Exiting... Bye!")
break
else:
print("Invalid choice! Try again.")

Output
--- Stack Menu ---
1. Push
2. Pop
3. Display
4. Exit
Enter choice: 1
Enter value to push: 10
10 pushed onto stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter choice: 1
Enter value to push: 20
20 pushed onto stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter choice: 3
Stack (top → bottom): [20, 10]

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter choice: 2
20 popped from stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter choice: 4 Exiting...
Bye!

Infix → Postfix Conversion


# Function to define operator precedence
def precedence(op):
if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
if op == '^':
return 3
return 0

# Function to check if character is operand def


is_operand(ch):
return ch.isalnum()

# Function to convert infix to postfix def


infix_to_postfix(expression):
stack = [] # operator stack
result = [] # output list

for ch in expression:
if is_operand(ch):
result.append(ch) # operand goes to output
elif ch == '(':
stack.append(ch)
elif ch == ')':
while stack and stack[-1] != '(':
result.append(stack.pop())
stack.pop() # remove '('
else: # operator
while (stack and precedence(stack[-1]) >= precedence(ch)):
result.append(stack.pop())
stack.append(ch)

# Pop remaining operators while


stack:
result.append(stack.pop())
return "".join(result)

# Driver code
if name == " main ":
exp = input("Enter infix expression: ")
postfix = infix_to_postfix(exp)
print("Postfix expression:", postfix)

Output
Enter infix expression: A+B*C
Postfix expression: ABC*+

Enter infix expression: (A+B)*C


Postfix expression: AB+C*

Enter infix expression: A+B*C-D/E


Postfix expression: ABC*+DE/-

Postfix to Infix
def postfix_to_infix(expression):
stack = []

for ch in expression:
if ch.isalnum(): # Operand
stack.append(ch)
else: # Operator
op2 = stack.pop()
op1 = stack.pop()
new_expr = "(" + op1 + ch + op2 + ")"
stack.append(new_expr)

return stack[-1]

# Driver code
if name == " main ":
exp = input("Enter postfix expression:
") infix = postfix_to_infix(exp)
print("Infix expression:", infix)
Output
Enter postfix expression: ABC*+
Infix expression: (A+(B*C))

Enter postfix expression: AB+C*


Infix expression: ((A+B)*C)

Enter postfix expression: ABC*+DE/-


Infix expression: ((A+(B*C))-(D/E))

Infix to Prefix
# Function to define precedence of operators
def precedence(op):
if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
if op == '^':
return 3
return 0

# Function to check if character is operand


def is_operand(ch):
return ch.isalnum()

# Function to convert infix to prefix


def infix_to_prefix(expression):
# Step 1: Reverse the infix expression
expression = expression[::-1]
expression = list(expression)

# Step 2: Swap ( and )


for i in range(len(expression)):
if expression[i] == '(':
expression[i] = ')'
elif expression[i] ==
')':
expression[i] = '('

# Step 3: Convert reversed expression to postfix


stack = []
result = []

for ch in expression:
if is_operand(ch):
result.append(ch)
elif ch == '(':
stack.append(ch)
elif ch == ')':
while stack and stack[-1] != '(':
result.append(stack.pop())
stack.pop()
else: # Operator
while stack and precedence(stack[-1]) >= precedence(ch):
result.append(stack.pop())
stack.append(ch)

while stack:
result.append(stack.pop())

# Step 4: Reverse postfix result → prefix


return "".join(result[::-1])

# Driver code
if name == " main ":
exp = input("Enter infix expression: ")
prefix = infix_to_prefix(exp)
print("Prefix expression:", prefix)

Output
Enter infix expression: A+B*C
Prefix expression: +A*BC

Enter infix expression: (A+B)*C


Prefix expression: *+ABC

Enter infix expression: A+B*C-D/E


Prefix expression: -+A*BC/DE

Prefix to infix
def prefix_to_infix(expression):
stack = []

# Traverse the expression in reverse


for ch in expression[::-1]:
if ch.isalnum(): # Operand
stack.append(ch)
else: # Operator
op1 = stack.pop()
op2 = stack.pop()
new_expr = "(" + op1 + ch + op2 + ")"
stack.append(new_expr)

return stack[-1]

# Driver code
if name == " main ":
exp = input("Enter prefix expression:
") infix = prefix_to_infix(exp)
print("Infix expression:", infix)

Output
Enter prefix expression: +A*BC
Infix expression: (A+(B*C))

Enter prefix expression: *+ABC


Infix expression: ((A+B)*C)

Enter prefix expression: -+A*BC/DE


Infix expression: ((A+(B*C))-(D/E))

Queue

queue = []

# Enqueue
queue.append('A')
queue.append('B')
queue.append('C')
print("Queue: ", queue)

# Peek
frontElement = queue[0]
print("Peek: ", frontElement)

# Dequeue
poppedElement = queue.pop(0)
print("Dequeue: ", poppedElement)
print("Queue after Dequeue: ", queue)

# isEmpty
isEmpty = not bool(queue)
print("isEmpty: ", isEmpty)

# Size
print("Size: ", len(queue))

Output

Queue: ['A', 'B', 'C']


Peek: A
Dequeue: A
Queue after Dequeue: ['B', 'C']
isEmpty: False
Size: 2

You might also like