/* * expr ::= term | term + expr * term ::= factor | factor * term * factor ::= (expr) | num * num ::= 0..9 */ var s = "((4+5)*3+2)*8"; var i = 0; function gettoken () { return s[i++]; } function tokenback () { i--; } function expr () { var x; var y = 0; x = term (); if (gettoken () == '+') y = expr (); else tokenback (); return x+y; } function term () { var x; var y = 1; x = factor (); if (gettoken () == '*') y = term (); else tokenback (); return x*y; } function factor () { var s = gettoken (); var x = parseInt (s); if (s == '(') { x = expr (); if (gettoken () != ')') console.log ("Error"); } else if ((x >= 0) \&\& (x <= 9)); else console.log ("Error"); return x; } console.log(expr()); console.log(((4+5)*3+2)*8);
Muss ich noch dran arbeiten
# 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())