# expr ::= term | term + expr # term ::= factor | factor * term # factor ::= (expr) | num s="((4+5)*3+2)*8" i=0 def gettoken (): global i j=i print(s[i]) if i < len(s)-1: i=i+1 return s[j] else: return 'e' def tokenback (): global i i = i-1 def expr (): y = 0 x = term () p = gettoken () if p == '+': y = expr () elif p == 'e': return x else: tokenback () return x+y def term (): y = 1 x = factor () if x == -1: return 1 p = gettoken () if p == '*': y = term () elif p == 'e': return x else: tokenback () return x*y def factor (): p = gettoken () if p.isdigit(): x = int(p) elif p == '(': x = expr () if gettoken () != ')': print ("error - Bracket not closed"); exit () elif p == 'e': return -1 else: print ("error - invalid character") exit () return x print(expr())