arithmetic expression reader in python

python

Solution

Here's some working code to get you started using `ast`:

import ast

s = 'subtract(4,add(4,times(3,4)))'

# Probably better to use functions from the operator module here :-)
functions = {'subtract': lambda a,b: a-b,
             'add': lambda a, b: a+b,
             'times': lambda a,b: a*b}


def _evaluate(node):
    if isinstance(node, ast.Num):
        return node.n
    elif isinstance(node, ast.Name):
        return functions[node.id]
    elif isinstance(node, ast.Call):
        function = _evaluate(node.func)
        return function(*[_evaluate(n) for n in node.args])
    else:
        raise ValueError('Unknown node type: %s', type(node))


def evaluate(s):
    tree = ast.parse(s)
    node = tree.body[0].value
    return _evaluate(node)

print evaluate(s)

Problem

I am trying to make an expression reader in python to compute basic arithmetic. given the expression `subtract(4,add(4,times(3,4)))` --> -12 What would be the most pythonic way to build this? My method would be to convert the expression to a string, then create many if statements or switch cases to find keywords such as `add`,`subtract`, or `times`. Then read the `(`, read an integer and comma, and then run the if statement/switch case again. If a `)` is ever encountered, that is when compute the required arithmetic of the latest key work. Pretty much storing key works and integers in a queue and computing the latest `subtract`,`times`, or `add` in the queue when `)` is found. This to me seems a bit too much. I was wondering if there are any useful built in functions in python that would make the code pythonic or easier to read

Original source