468,316 Members | 2,065 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,316 developers. It's quick & easy.

help with recursion on GP project

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([]):
if type(tree[2]) == type([]):
if type(tree[1]) == type([]):
Jan 14 '07 #1
1 1189
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))
return expr

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

But it's rather slow...


Jan 14 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Peri | last post: by
3 posts views Thread by Thomas Philips | last post: by
5 posts views Thread by Ioannis Vranos | last post: by
4 posts views Thread by pauldepstein | last post: by
24 posts views Thread by proctor | last post: by
4 posts views Thread by Luke Davis | last post: by
10 posts views Thread by Jonathan Wood | last post: by
1 post views Thread by teejayem | last post: by
35 posts views Thread by Muzammil | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.