python_lab 4 24MSD7001
python_lab 4 24MSD7001
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).
if char.isalnum():
operand = []
while i < len(expression) and expression[i].isalnum():
operand.append(expression[i])
i += 1
operand = ''.join(operand)
if operand in variables:
postfix.append(str(variables[operand]))
else:
postfix.append(operand)
continue
else:
while stack and precedence(stack[-1]) >= precedence(char):
postfix.append(stack.pop())
stack.append(char)
i += 1
while stack:
postfix.append(stack.pop())
if __name__ == "__main__":
variables = {}
for char in set(infix_expr):
if char.isalpha():
value = float(input(f"Enter the value of {char}: "))
variables[char] = value
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.
binary_rep = bin(operand)[2:]
stack.append((operand, binary_rep))
print(f"Push: {operand} as ({operand}, '{binary_rep}')")
else:
operand2, bin2 = stack.pop()
operand1, bin1 = stack.pop()
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:]
stack.append((result, binary_result))
print(f"Stack: {stack}")
# Final result
result, binary_result = stack.pop()
print(f"Final result: {result} with binary representation {binary_result}")
return result
In [ ]: