[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

How to dynamic insert more conditional statements into a function

Sheng

3/9/2010 9:49:00 PM

Hi I am a newbie for Python

Here is a question, say I have a list L,

function foo is:

def foo(L):
if L[0] > 0: return True

if later I want another function goo which returns "True" when L[0]
and L[1] are both > 0, i.e.,

def goo(L):
if L[0] > 0 and L[1] > 0: return True

Can anybody tell me how can I write the function "goo" based upon the
function "foo"? Thanks!
I know if it is implementable, I should use "decorator". But I just
cannot figure out how.
2 Answers

Emile van Sebille

3/9/2010 10:22:00 PM

0

On 3/9/2010 1:48 PM Shane said...
> Hi I am a newbie for Python
>
> Here is a question, say I have a list L,
>
> function foo is:
>
> def foo(L):
> if L[0]> 0: return True
>
> if later I want another function goo which returns "True" when L[0]
> and L[1] are both> 0, i.e.,
>
> def goo(L):
> if L[0]> 0 and L[1]> 0: return True


Here's one way...

def foo(L,deep=0):
return L[0] and not deep or foo(L[1:],deep-1)

Subject to clean up.

Emile

Gabriel Genellina

3/10/2010 6:35:00 AM

0

En Tue, 09 Mar 2010 18:48:42 -0300, Shane <shengcer@gmail.com> escribió:

> Hi I am a newbie for Python
>
> Here is a question, say I have a list L,
>
> function foo is:
>
> def foo(L):
> if L[0] > 0: return True
>
> if later I want another function goo which returns "True" when L[0]
> and L[1] are both > 0, i.e.,
>
> def goo(L):
> if L[0] > 0 and L[1] > 0: return True
>
> Can anybody tell me how can I write the function "goo" based upon the
> function "foo"? Thanks!
> I know if it is implementable, I should use "decorator". But I just
> cannot figure out how.

To implement goo based on foo:

def goo(L):
if foo(L) and L[1]>0: return True

I don't see how to use a decorator here - maybe your example became too
simple to be useful. A more realistic use case?

--
Gabriel Genellina