Q1: Write a program to convert an infix expression to a postfix expression with the following modifications: o The infix expression
can include variables (e.g., a + b * c) and constants. o Before the conversion, the program must prompt the user to input the values of the variables (e.g., if
a = 5, b = 2, and c = 8, replace variables in the expression). o The program should handle unary minus (e.g., -a + b).
In [5]: def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
def apply_operator(operators, values):
right = [Link]()
left = [Link]()
operator = [Link]()
if operator == '+':
[Link](left + right)
elif operator == '-':
[Link](left - right)
elif operator == '*':
[Link](left * right)
elif operator == '/':
[Link](left / right)
def handle_unary_minus(expression):
result = []
i = 0
while i < len(expression):
if expression[i] == '-' and (i == 0 or expression[i - 1] in "(+-*/"):
[Link]('0')
[Link](expression[i])
i += 1
return ''.join(result)
def infix_to_postfix(expression, variables):
expression = handle_unary_minus(expression)
stack = []
postfix = []
i = 0
while i < len(expression):
char = expression[i]
if [Link]():
operand = []
while i < len(expression) and expression[i].isalnum():
[Link](expression[i])
i += 1
operand = ''.join(operand)
if operand in variables:
[Link](str(variables[operand]))
else:
[Link](operand)
continue
elif char == '(':
[Link](char)
elif char == ')':
while stack and stack[-1] != '(':
[Link]([Link]())
[Link]() # Pop '('
else:
while stack and precedence(stack[-1]) >= precedence(char):
[Link]([Link]())
[Link](char)
i += 1
while stack:
[Link]([Link]())
return ' '.join(postfix)
if __name__ == "__main__":
infix_expr = input("Enter the infix expression: ")
variables = {}
for char in set(infix_expr):
if [Link]():
value = float(input(f"Enter the value of {char}: "))
variables[char] = value
postfix_expr = infix_to_postfix(infix_expr, variables)
print("Postfix Expression:", postfix_expr)
Postfix Expression: 0 3.0 - + 2.0 * 6.0 / 5.0
2. Write a program to evaluate the postfix expression generated from the previous step with the following conditions:
o Each operand should be pushed onto the stack as a tuple, where the first value is the operand itself, and the second value is its binary representation as a string. For example: Push 5 as (5, "101") Push 3 as (3, "11") o When evaluating the postfix expression, the program should
print intermediate steps of the stack showing the tuples at each stage.
In [6]: def evaluate_postfix(postfix_expression):
stack = []
# Split into chunks
tokens = postfix_expression.split()
for token in tokens:
if [Link]():
operand = int(token)
binary_rep = bin(operand)[2:]
[Link]((operand, binary_rep))
print(f"Push: {operand} as ({operand}, '{binary_rep}')")
else:
operand2, bin2 = [Link]()
operand1, bin1 = [Link]()
if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2
binary_result = bin(result)[2:]
[Link]((result, binary_result))
print(f"After {operand1} {token} {operand2}: Push result {result} as ({result}, '{binary_result}')")
print(f"Stack: {stack}")
# Final result
result, binary_result = [Link]()
print(f"Final result: {result} with binary representation {binary_result}")
return result
postfix_expression = "5 3 +"
evaluate_postfix(postfix_expression)
Push: 5 as (5, '101')
Stack: [(5, '101')]
Push: 3 as (3, '11')
Stack: [(5, '101'), (3, '11')]
After 5 + 3: Push result 8 as (8, '1000')
Stack: [(8, '1000')]
Final result: 8 with binary representation 1000
Out[6]: 8
In [ ]: