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]) 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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:
|
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):
|
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.
|
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
|
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?
| |
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
|
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...
|
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
|
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
|
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 ??
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |