473,757 Members | 10,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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([]):
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])
Jan 14 '07 #1
1 1339
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(evalua te, ops))
else:
return expr

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

But it's rather slow...

Bye,
bearophile

Jan 14 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3422
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this:
3
1541
by: Thomas Philips | last post by:
I'm teaching myself Python and never having used recursion and generators, created the simple recursive program shown below and single stepped through it in IDLE with the debugger turned on to get a feel for how recursion and generators worked. def testRecursion(n): if n == 1: yield else: for result in testRecursion(n-1):
5
1284
by: Ioannis Vranos | last post by:
The following code is supposed to print all folder names of a folder but it does not work. Why? Change the folder in main() to a folder suitable for your system so as to test it. I created this proof-of-concept example, because I encountered similar recursion problems in a more complex project.
4
1573
by: pauldepstein | last post by:
I am writing code to price some financial options using recursive functions. It compiles but I get a runtime error which is caused by a memory violation. The problem is that the code is much too long to be suitable for inclusion in this posting, and I don't know where the problem lies. If anyone does have the time/willingness/extreme kindness to help me, I
24
2548
by: proctor | last post by:
hello, i have a small function which mimics binary counting. it runs fine as long as the input is not too long, but if i give it input longer than 8 characters it gives RuntimeError: maximum recursion depth exceeded in cmp i'm not too sure what i am doing improperly. is there really a lot of recursion in this code?
7
1610
by: Joey | last post by:
VS2005 asp.net 2.0 C# Developing with File System/Cassini instead of IIS (publish to IIS every so often) Hello guys, I have a web app where I am using static variables on many pages to maintain values between postbacks. I am also using several static
4
1429
by: Luke Davis | last post by:
I've been programming in C# for about 3 months now and I've completed a previous project that worked a lot with data, so I know the basics. This is what I need to do, try and see what you would do as an expert C# programmer. I have to make a paired sales analysis which takes the same home sold twice in a given time span and show how the price has changed to show true market conditions. Right now we have 120,000 rows of data that have...
10
1605
by: Jonathan Wood | last post by:
I'm taking my first stab at using ASP.NET memberships and could use some help. I'm following along in a book, which recommends I use the Web Application Administration Tool in VS 2005. A couple of problems: 1. The only choices it gives me for the authentication method are Windows and Passport. Based on what I read, forms is what I need. Can anyone tell me
1
999
by: teejayem | last post by:
I have created a UserControl within a Class Library Project type. I will be using this as I want the object to perform some ClientSide scripts. I have built the project and copied the DLL to the root of my aspx page and have used the following tag within my aspx page. <objectid="CleintControl" ClassID="ClientControl.dll#ClientControl.Main></object> For some reason no matter what I do the object does not render into my
35
4738
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.