8
devlife
7y

My very first calculator app ;)
eval('2+2');

Comments
  • 0
    @Nanos
    Errors are any where my friend:)
  • 3
    Eyyy, that's pretty cool.
    Check this one out I made for another comment saying a similar thing.

    # Lexical Analysis,
    def lex(code):
    code = code.replace('(', ' ( ')
    code = code.replace(')', ' ) ')
    return [x for x in code.split(' ') if x]

    # Parsing stage,
    def parse(tokens):
    tree = []
    stack = []
    work = tree
    for token in tokens:
    if token == '(':
    work += [[]]
    stack += [work]
    work = work[-1]
    elif token == ')':
    work = stack.pop()
    else:
    work += [token]
    return tree

    def evaluate(ast):
    for token in ast:
    if type(token) is list:
    return evaluate(token)
    elif token.isdigit():
    return int(token)
    elif token == '+':
    return sum(evaluate([x]) for x in ast[1:])

    code = '(+ 1 (+ 1 1))'
    print(evaluate(parse(lex(code))))

    Now it only does addition, but wouldn't be hard to add more.
Add Comment