473,587 Members | 2,324 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursive function returning a list

Hello!

I have got a Python "Device" Object which has got a attribute (list)
called children which my contain several other "Device" objects. I
implemented it this way in order to achieve a kind of parent/child
relationship.

Now I would like to get all children of a given "Device" object and
thought that it would be the best way to use recursive function.

This is what I got so far:

def getAllChildren( self, children=[]):
if self.children:
children.extend (self.children)
for child in self.children:
child.getAllChi ldren(children)
return children

Unfortunately, it doesn't work like expected since the default parameter
children=[] is evaluated only once. That's why the children list becomes
larger and larger after calling the method several times but I can't
think of another possibility.

Do you have any ideas?
Jul 17 '06 #1
14 3466
In <e9************ *@news.t-online.com>, Fabian Steiner wrote:
This is what I got so far:

def getAllChildren( self, children=[]):
if self.children:
children.extend (self.children)
for child in self.children:
child.getAllChi ldren(children)
return children

Unfortunately, it doesn't work like expected since the default parameter
children=[] is evaluated only once. That's why the children list becomes
larger and larger after calling the method several times but I can't
think of another possibility.

Do you have any ideas?
def get_all_childre n(self, accumulator=Non e):
if accumulator is None:
accumulator = list()
accumulator.ext end(self.childr en)
for child in self.children:
child.get_all_c hildren(accumul ator)
return accumulator

Ciao,
Marc 'BlackJack' Rintsch

Jul 17 '06 #2
Fabian Steiner wrote:
Hello!

I have got a Python "Device" Object which has got a attribute (list)
called children which my contain several other "Device" objects. I
implemented it this way in order to achieve a kind of parent/child
relationship.

Now I would like to get all children of a given "Device" object and
thought that it would be the best way to use recursive function.

This is what I got so far:

def getAllChildren( self, children=[]):
if self.children:
children.extend (self.children)
for child in self.children:
child.getAllChi ldren(children)
return children

Unfortunately, it doesn't work like expected since the default parameter
children=[] is evaluated only once. That's why the children list becomes
larger and larger after calling the method several times but I can't
think of another possibility.

Do you have any ideas?
This is a standard question, and has a standard answer: replace

def getAllChildren( self, children=[]):

with

def getAllChildren( self, children=None):
if children is None:
children = []

That way a new empty list is created for each call that receives no
"children" argument. Otherwise the same (once-empty) list is used for
them all.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jul 17 '06 #3
Do you have any ideas?

you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild
Jul 18 '06 #4
Boris Borcic wrote:
>Do you have any ideas?


you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild

Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 18 '06 #5
Hello Bruno,

Bruno Desthuilliers wrote:
Boris Borcic wrote:
>>Do you have any ideas?

you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild


Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)
Sorry, but I don't understand your reasoning. How can you exclude that the OP
/may/ find that a generator neatly solves his problem ? The use of a default
value was not an end in itself, was it ?- and the quirks of default values being
FAQ stuff don't change that. Sure if nobody had covered that aspect, but a
couple other posters did...

Mmmmhhh somehow it feels like if there is any issue here, it is about defending
the credo "there ought to exist only one obvious way to do it" ?...

Cheers, BB
--
666 ?? - 666 ~ .666 ~ 2/3 ~ 1-1/3 ~ tertium non datur ~ the excluded middle
~ "either with us, or against us" !!
Jul 18 '06 #6
Boris Borcic a écrit :
Hello Bruno,

Bruno Desthuilliers wrote:
>Boris Borcic wrote:
>>>Do you have any ideas?
you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild

Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)

Sorry, but I don't understand your reasoning.
It's quite simple. The OP's problem is well-known (it's a FAQ), and easy
to solve. The righ answer to it is obviously to give a link to the FAQ
(or take time to re-explain it for the zillionth time), not to propose a
workaround.
How can you exclude that
the OP /may/ find that a generator neatly solves his problem ?
I don't exclude it, and explicitly mentioned in whole letters that, I
quote, it "may be a pretty good idea". And actually, the OP's problem is
really with default values evaluation scheme - something that every
Python programmer should know, because there are cases where you cannot
solve it with a generator-based solution !-)
The use
of a default value was not an end in itself, was it ?
If the OP has other reasons to want to use an accumulator based solution
- which we don't know - then the possibility to use a default value is
important.
- and the quirks of
default values being FAQ stuff don't change that. Sure if nobody had
covered that aspect, but a couple other posters did...
Yes, but you forgot to mention that - and I would not have post any
comment on your solution if you had explicitly mentioned the FAQ or
these other answers.
Mmmmhhh somehow it feels like if there is any issue here, it is about
defending the credo "there ought to exist only one obvious way to do it"
?...
Nope, it's about trying to make sure that anyone googling for a similar
problem will notice the canonical solution somehow.

Jul 18 '06 #7
Bruno Desthuilliers wrote:
Boris Borcic a écrit :
Hello Bruno,

Bruno Desthuilliers wrote:
Boris Borcic wrote:

Do you have any ideas?
you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild

Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)
Sorry, but I don't understand your reasoning.

It's quite simple. The OP's problem is well-known (it's a FAQ), and easy
to solve. The righ answer to it is obviously to give a link to the FAQ
(or take time to re-explain it for the zillionth time), not to propose a
workaround.
How can you exclude that
the OP /may/ find that a generator neatly solves his problem ?

I don't exclude it, and explicitly mentioned in whole letters that, I
quote, it "may be a pretty good idea". And actually, the OP's problem is
really with default values evaluation scheme - something that every
Python programmer should know, because there are cases where you cannot
solve it with a generator-based solution !-)
The use
of a default value was not an end in itself, was it ?

If the OP has other reasons to want to use an accumulator based solution
- which we don't know - then the possibility to use a default value is
important.
- and the quirks of
default values being FAQ stuff don't change that. Sure if nobody had
covered that aspect, but a couple other posters did...

Yes, but you forgot to mention that - and I would not have post any
comment on your solution if you had explicitly mentioned the FAQ or
these other answers.
Mmmmhhh somehow it feels like if there is any issue here, it is about
defending the credo "there ought to exist only one obvious way to do it"
?...

Nope, it's about trying to make sure that anyone googling for a similar
problem will notice the canonical solution somehow.
Sorry, but I kinda agree with Boris here. Not that I am anybody here,
really.

If the question is to use an accumulator based solution, then yes, the
default values answer is definitely the canonical solution.
If the question is to write a recursive function that returns a list,
an accumulator based solution and a generator based solution are two
different ways for doing that. I don't think there is actually a FAQ
saying you must use the accumulator solution.
Actually, the accumulator based solution kind of comes to me
automatically as standard in any programming language, and I believe
that this was established as standard in python, _before_ the
introduction of generators.

Now, personally I find the generator-based solution more intuitive for
me (in the eys of the beholder:). And, looking at the subject of the
thread, guess what was the question?

k

Jul 19 '06 #8
Bruno Desthuilliers wrote:
Boris Borcic a écrit :
>>Hello Bruno,

Bruno Desthuilliers wrote:
[...]
>>>Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)

Sorry, but I don't understand your reasoning.


It's quite simple. The OP's problem is well-known (it's a FAQ), and easy
to solve. The righ answer to it is obviously to give a link to the FAQ
So, why didn't you?
(or take time to re-explain it for the zillionth time), not to propose a
workaround.
Or did I miss something?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jul 19 '06 #9
Bruno Desthuilliers wrote:
Boris Borcic a écrit :
>Hello Bruno,

Bruno Desthuilliers wrote:
>>Boris Borcic wrote:

Do you have any ideas?
you could use a recursive generator, like

def genAllChildren( self) :
for child in self.children :
yield child
for childchild in child.genAllChi ldren() :
yield childchild

Or how to *not* address the real problem...

Boris, using a generator may be a pretty good idea, but *not* as a way
to solve a problem that happens to be a FAQ !-)

Sorry, but I don't understand your reasoning.
It's quite simple. The OP's problem is well-known (it's a FAQ),
This is really an oversimplificat ion. What's the case is that his showstopper
was covered by the FAQ list. The OP's "problem" is actually a stack of
problems/subproblems and was presented as such.
and easy
to solve.
I did consider a couple distinct ways to solve "it" while passing lists around -
did you notice that the OP's code made no clear choice as to whether it wanted
to pass them by reference or as return values ? That's how a generator struck me
as most pythonic if you want ("In the face of ambiguity, refuse the temptation
to guess").
The righ answer to it is obviously to give a link to the FAQ
(or take time to re-explain it for the zillionth time), not to propose a
workaround.
Given your usage of code simplicity in another thread as (roughly) a measure of
pythonic virtue, I feel it warranted to ask why should one recognize simpler
code as "the workaround" (assuming it fits the bill) ?

Because it doesn't cross the FAQ, seems to be your answer...
>How can you exclude that the OP /may/ find that a generator neatly
solves his problem ?
I don't exclude it, and explicitly mentioned in whole letters that, I
quote, it "may be a pretty good idea". And actually, the OP's problem is
really with default values evaluation scheme - something that every
Python programmer should know, because there are cases where you cannot
solve it with a generator-based solution !-)
...
>- and the quirks of default values being FAQ stuff don't change that.
Sure if nobody had covered that aspect, but a couple other posters did...

Yes, but you forgot to mention that - and I would not have post any
comment on your solution if you had explicitly mentioned the FAQ or
these other answers.
At this point I recognize that our difference may very well have deep roots
relating to cognitive style, educational policy, etc. Generally speaking I
welcome debate on such premisses as an occasion to learn more (not so much from
my contradictor than from the debate itself), but a precondition is that the
partner/contradictor understands my motive (what I can't count on since the idea
of learning from the debate itself is pretty typical such cognitive style
divides). Besides, I don't quite have the time right now.

The short form is : "I strongly disagree with you".

Best, BB
--
"On naît tous les mètres du même monde"
Jul 19 '06 #10

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

Similar topics

2
3119
by: replace-this-with-my-name | last post by:
Hi. How do I return a string containing an entire menu-tree from a recursive function? Here is my current recursive function: function page_tree( $_i ){ //Call global mysql connection variable
4
3146
by: Derek Rhodes | last post by:
using Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32 OK, I have a recursive function that should return a list, but doesn't <start session> def test(word): if type(word) == str:
10
5658
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom...
2
1975
by: actuary77 | last post by:
I am trying to write simple recursive function to build a list: def rec(n,alist=): _nl=alist print n,_nl if n == 0: print n,_nl return _nl else:
7
567
by: Jon Slaughter | last post by:
#pragma once #include <vector> class empty_class { }; template <int _I, int _J, class _element, class _property> class RDES_T {
11
2761
by: randomtalk | last post by:
hi, i have the following recursive function (simplified to demonstrate the problem): >>> def reTest(bool): .... result = .... if not bool: .... reTest(True) .... else: .... print "YAHHH" .... result =
3
2947
by: samuelberthelot | last post by:
Hi, I'm trying to write a recursive fucntion that takes as parameters a html div and an id. I have to recurse through all the children and sub-children of the div and find the one that matches the id. I have the following but it doesn't work well (algorighm issue) : var cn = null; function getChildElement(parent, childID){ for (var i=0;...
10
2547
by: AsheeG87 | last post by:
Hello Everyone! I have a linked list and am trying to include a recursive search. However, I am having trouble understanding how I would go about that. I don't quite understand a recursive search....would any of you be so kind to explain it to me...maybe include some examples. I would GREATLY appreciate it!!!
6
9600
KevinADC
by: KevinADC | last post by:
This snippet of code provides several examples of programming techniques that can be applied to most programs. using hashes to create unique results static variable recursive function serialization The code itself generates a list of strings comprised of random numbers. No number will be repeated within a string, and no string will...
0
7843
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...
0
8206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5713
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...
0
3840
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...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
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...

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.