import sys
class Exp:
def __init__(self, pos, op):
self.pos = pos
self.op = op
i, j, no, tmpch = 1, 0, 0, 90 # tmpch starts at ASCII 'Z'
k = []
left = ""
right = ""
def findopr(expr):
global k, j
k = [] # Reset k to avoid residual values
operators = [":", "/", "*", "+", "-"]
for op in operators:
for idx, char in enumerate(expr):
if char == op:
k.append(Exp(idx, op))
def fleft(expr, x):
global left
w = ""
flag = 0
x -= 1
while x >= 0 and expr[x] not in "+-*/=:": # Consider '=' as stop point
if expr[x] != "$" and flag == 0:
w = expr[x] + w
expr[x] = "$"
flag = 1
x -= 1
left = w
def fright(expr, x):
global right
w = ""
flag = 0
x += 1
while x < len(expr) and expr[x] not in "+-*/=:":
if expr[x] != "$" and flag == 0:
w += expr[x]
expr[x] = "$"
flag = 1
x += 1
right = w
def explore(expr):
global i, tmpch, no
expr = list(expr) # Convert to list to allow mutation
i=0
while i < len(k) and k[i].op:
fleft(expr, k[i].pos)
fright(expr, k[i].pos)
expr[k[i].pos] = chr(tmpch)
print(f"\t{chr(tmpch)} := {left} {k[i].op} {right}")
tmpch -= 1
i += 1
fright(expr, -1)
if no == 0 and k:
fleft(expr, len(expr))
print(f"\t{right} := {expr[k[i - 1].pos]}")
sys.exit(0)
if k:
print(f"\t{right} := {expr[k[i - 1].pos]}")
def main():
print("\t\tINTERMEDIATE CODE GENERATION\n")
expr = input("Enter the Expression: ")
print("The intermediate code:")
findopr(expr)
explore(expr)
if __name__ == "__main__":
main()
INTERMEDIATE CODE GENERATION
Enter the Expression: a+b*c-d/e+f*g-h
The intermediate code:
Z := d / e
Y := b * c
X := f * g
W := a + Y
V := Z + X
U := W - V
T := U - h
T := $