Re: JavaScript, Python

Sorry, dass das so lange gedauert hat, eine Variable war falsch benannt

# expr ::= expr + term | term
# term ::= term * factor | factor
# factor ::= '(' expr ')' | const

# Bzw.

# expr ::= term | term '+' expr
# term ::= factor | factor '*' term
# factor ::= '(' expr ')' | const

# const ::= '9', '8', ..., '0'

i=0
s = "((4+5*(4+2))+1)*3";

def nexttoken ():
    global i
    j = i
    if i >= len(s):
        return 'e'
    i = i+1
    return s[j]

def tokenback ():
    global i
    i = i-1

def expr ():
    y = 0

    x = term()
    s = nexttoken ()
    if s == '+':
        y = expr()
    elif s == 'e':
        return x+y
    else:
        tokenback()
    return x+y

def term ():
    y = 1

    x = factor()
    s = nexttoken ()
    if s == '*':
        y = term ()
    elif s == 'e':
        return x*y
    else:
        tokenback()
    return x*y

def factor ():
    s = nexttoken ()
    if s.isdigit ():
        y = int(s)

    if s == '(':
        x = expr()
        if nexttoken () != ')':
            exit ()
    elif s == 'e':
        return 0
    elif (y >= 0) and (y <= 9):
        x = y
    else:
        exit ()
    return x

print(expr())