help with recursion on GP project

N

none

I'm trying to create a recursive function to evaluate the expressions
within a list. The function uses eval() to evaluate the list. Like a
lisp interpreter but very limited.
What I'm looking for is a function to recursively traverse the list and
provide answers in place of lists, so that ...
Example = ['add', ['sub', 5, 4], ['mul', 3, 2]]
Becomes: Example = ['add', 1, 6]
Becomes: Example = 7
*Functions are defined in the script

The code I currently have, which isn't pretty (bottom), doesn't work
because it doesn't return the value of the evaluated list. But I can't
figure out how to do that. Any help would be greatly appreciated.

Jack Trades


def recursive(tree):
if type(tree[1]) != type([]) and type(tree[2]) != type([]):
eval(a[0]+'('+str(tree[1])+','+str(tree[2])+')')
if type(tree[2]) == type([]):
recursive(tree[2])
if type(tree[1]) == type([]):
recursive(tree[1])
 
B

bearophileHUGS

First possible raw solution:

from operator import add, sub, mul, div, neg

def evaluate(expr):
if isinstance(expr, list):
fun, ops = expr[0], expr[1:]
return fun(*map(evaluate, ops))
else:
return expr

example = [add, [add, [sub, 5, 4], [mul, 3, 2]], [neg, 5]]
print evaluate(example)

But it's rather slow...

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top