0% found this document useful (0 votes)
16 views

python_lab 4 24MSD7001

Uploaded by

tarun.24msd7001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

python_lab 4 24MSD7001

Uploaded by

tarun.24msd7001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 = values.pop()
left = values.pop()
operator = operators.pop()
if operator == '+':
values.append(left + right)
elif operator == '-':
values.append(left - right)
elif operator == '*':
values.append(left * right)
elif operator == '/':
values.append(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 "(+-*/"):
result.append('0')
result.append(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 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

elif char == '(':


stack.append(char)

elif char == ')':


while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # Pop '('

else:
while stack and precedence(stack[-1]) >= precedence(char):
postfix.append(stack.pop())
stack.append(char)

i += 1

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

return ' '.join(postfix)

if __name__ == "__main__":

infix_expr = input("Enter the infix expression: ")

variables = {}
for char in set(infix_expr):
if char.isalpha():
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 token.isdigit():
operand = int(token)

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"After {operand1} {token} {operand2}: Push result {result} as ({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

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 [ ]:

You might also like