def Main():
t=int(input())
cs=1
while t>0:
print("Expression #%d:"%cs,end=' ')
cs+=1
t-=1
n=int(input())
dict={}
last={}
ans=""
var,eq,a,op,b=None,None,None,None,None
for i in range(n):
var,eq,a,op,b=input().split()
if op=='+':
if a.isdecimal() and b.isdecimal():
dict[var]=a+op+b
elif not a.isdecimal() and b.isdecimal():
dict[var]=dict[a]+'+'+b
elif not b.isdecimal() and a.isdecimal():
if last[b]==op:
dict[var]=a+'+('+dict[b]+')'
else:
dict[var]=a+op+dict[b]
else:
if last[a]!=op and last[b]!=op or last[a]==op and last[b]!=op:
dict[var]=dict[a]+op+dict[b]
else:
dict[var]=dict[a]+'+('+dict[b]+')'
else:
if a.isdecimal() and b.isdecimal():
dict[var]=a+op+b
elif not a.isdecimal() and b.isdecimal():
if last[a]==op:
dict[var]=dict[a]+op+b
else:
dict[var]='('+dict[a]+')*'+b
elif not b.isdecimal() and a.isdecimal():
dict[var]=a+'*('+dict[b]+')'
else:
if last[a]==op:
dict[var]=dict[a]+'*('+dict[b]+')'
else:
dict[var]='('+dict[a]+')*('+dict[b]+')'
last[var]=op
print(dict[var])
if __name__=="__main__":
Main()
t=int(input())
cs=1
while t>0:
print("Expression #%d:"%cs,end=' ')
cs+=1
t-=1
n=int(input())
dict={}
last={}
ans=""
var,eq,a,op,b=None,None,None,None,None
for i in range(n):
var,eq,a,op,b=input().split()
if op=='+':
if a.isdecimal() and b.isdecimal():
dict[var]=a+op+b
elif not a.isdecimal() and b.isdecimal():
dict[var]=dict[a]+'+'+b
elif not b.isdecimal() and a.isdecimal():
if last[b]==op:
dict[var]=a+'+('+dict[b]+')'
else:
dict[var]=a+op+dict[b]
else:
if last[a]!=op and last[b]!=op or last[a]==op and last[b]!=op:
dict[var]=dict[a]+op+dict[b]
else:
dict[var]=dict[a]+'+('+dict[b]+')'
else:
if a.isdecimal() and b.isdecimal():
dict[var]=a+op+b
elif not a.isdecimal() and b.isdecimal():
if last[a]==op:
dict[var]=dict[a]+op+b
else:
dict[var]='('+dict[a]+')*'+b
elif not b.isdecimal() and a.isdecimal():
dict[var]=a+'*('+dict[b]+')'
else:
if last[a]==op:
dict[var]=dict[a]+'*('+dict[b]+')'
else:
dict[var]='('+dict[a]+')*('+dict[b]+')'
last[var]=op
print(dict[var])
if __name__=="__main__":
Main()
Comments
Post a Comment