473,378 Members | 1,037 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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.getAllChildren(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 3439
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.getAllChildren(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_children(self, accumulator=None):
if accumulator is None:
accumulator = list()
accumulator.extend(self.children)
for child in self.children:
child.get_all_children(accumulator)
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.getAllChildren(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.genAllChildren() :
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.genAllChildren() :
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.genAllChildren() :
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.genAllChildren() :
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.genAllChildren() :
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.genAllChildren() :
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 oversimplification. 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
ma********@gmail.com wrote:
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.genAllChildren() :
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.
On what ?
Not that I am anybody here,
really.
Err... Are you you at least ?-)
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.
Note that the generator-based solution doesn't return a list. (And yes,
I know, it's just a matter of wrapping the call to obj.genAllChildrens()
in a list constructor).
I don't think there is actually a FAQ
saying you must use the accumulator solution.
Did I say so ? The FAQ I mention is about default values evaluation, and
it's the problem the OP was facing. Please re-read my post more carefully.
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.
FWIW, you don't need to pass an accumulator around to solve this problem:

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

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '06 #11
Steve Holden wrote:
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?
The fact that someone already did so ?
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '06 #12
Bruno Desthuilliers wrote:

Nope, it's about trying to make sure that anyone googling for a similar
problem will notice the canonical solution somehow.
Hey, I challenge you to cook up a plausible query even loosely fitting your
"googling for a similar problem" that would return my answer but not thatof the
other posters (nor the faq itself, oeuf corse).

Best, BB
--
"On naît tous les mètres du même monde"

Jul 19 '06 #13
Bruno Desthuilliers wrote:
ma********@gmail.com wrote:
[...]
Sorry, but I kinda agree with Boris here.

On what ?
On the argument that you are (implicitly?) disagreeing with him on,
obviously. That the OP problem is not definitely the default values
question. As you say:
>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.
My emphasis is on "we don't know".
>
Not that I am anybody here,
really.

Err... Are you you at least ?-)
I am. Thanks for your concern:)
Note that the generator-based solution doesn't return a list. (And yes,
I know, it's just a matter of wrapping the call to obj.genAllChildrens()
in a list constructor).
And you can do the wrapping in a function that returns a list, to be
more pedantic. And yes, I know you know.
>
I don't think there is actually a FAQ
saying you must use the accumulator solution.

Did I say so ? The FAQ I mention is about default values evaluation, and
it's the problem the OP was facing. Please re-read my post more carefully.
Actually, I have read your post right first time. And I do know you
didn't say that (a FAQ for accumulators). I raised it just in case.
What I don't agree with is that it is not the problem the OP was
facing. The discussion was: is the real problem the default values
problem, which he already got a solution for. Or was the real problem
the list returning recursion problem, for which he (or subsequent
google searchers, who are more likely to come to this thread after
searching for "Recursive function returning a list") may benefit from a
generator approach.
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.

FWIW, you don't need to pass an accumulator around to solve this problem:

def getAllChildren(self):
children = []
if self.children:
children.extend(self.children)
for child in self.children:
children.extend(child.getAllChildren())
return children
Thanks for the function, though I regard it as kind of trivial for the
level of discussion that we are having now. The problem solved by the
accumulator is _not_ the building of a list recursively. It is doing so
efficiently. Which is definitely not done by creating multiple
temporary lists just to add them. I am sure you know the theory. More
of relevance is that the generator based solution has also the same
efficiency, so they are both better than the trivial solution.
You have a point though. Your function is a solution. Just I don't
regard it as the preferred solution for the problem as I see it. YMMV.

To recap, the OP (and subsequent google searchers, if they pass by) has
now the preferred solution according to you. To my satisfaction, they
will also read the other solution, which looks more pythonic to me. As
I see it, any additional discussion now suffers from diminishing
returns.

Regards,
k

Jul 19 '06 #14
ma********@gmail.com wrote:
Bruno Desthuilliers wrote:
>>ma********@gmail.com wrote:

[...]
>>>Sorry, but I kinda agree with Boris here.

On what ?


On the argument that you are (implicitly?) disagreeing with him
it's getting messy - too much level of indirection !-)
on,
obviously. That the OP problem is not definitely the default values
question.
Ok, I do agree that it's only *one* part of the problem - the other
(implied) being "what other possible solutions".
As you say:

>>>>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.


My emphasis is on "we don't know".
At least we do agree on something !-)
>
>>>Not that I am anybody here,
really.

Err... Are you you at least ?-)


I am.
Great.
Thanks for your concern:)
!-)
>
(snip)
>>>I don't think there is actually a FAQ
saying you must use the accumulator solution.

Did I say so ? The FAQ I mention is about default values evaluation, and
it's the problem the OP was facing. Please re-read my post more carefully.


Actually, I have read your post right first time. And I do know you
didn't say that (a FAQ for accumulators). I raised it just in case.
What I don't agree with is that it is not the problem the OP was
facing. The discussion was: is the real problem the default values
problem, which he already got a solution for. Or was the real problem
the list returning recursion problem, for which he (or subsequent
google searchers, who are more likely to come to this thread after
searching for "Recursive function returning a list") may benefit from a
generator approach.
agreed.

(snip)
Thanks for the function, though I regard it as kind of trivial for the
level of discussion that we are having now. The problem solved by the
accumulator is _not_ the building of a list recursively. It is doing so
efficiently. Which is definitely not done by creating multiple
temporary lists just to add them. I am sure you know the theory. More
of relevance is that the generator based solution has also the same
efficiency, so they are both better than the trivial solution.
You have a point though. Your function is a solution. Just I don't
regard it as the preferred solution for the problem as I see it.
Nor do I.
>YMMV.
It doesn't
To recap, the OP (and subsequent google searchers, if they pass by) has
now the preferred solution according to you.
Please not that I didn't meant to present it as "the prefered solution".
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 20 '06 #15

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

Similar topics

2
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...
4
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
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. ...
2
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
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
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...
3
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...
10
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...
6
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.