2

I have a recursive function which loops through any number of objects, and their children collecting children who's age meets the filtered ages.

In this case I'm looking to loop through each Person and their children collecting any Person who's age is either 2 or 4. However I'm not entirely sure how to continuously build a single list and then return it. Right now it just returns the last found Person.

UPDATED I've made a few changes to the recursive function to always append to the passed variable. Is this a proper solution?

from random import randint

NODES = []

class Person():
    def __init__(self, name="", age=0, children=None):
        self.name = name
        self.age = (randint(0,4))
        self.children = children if children is not None else []

for x in xrange(5):
    new = Person()
    NODES.append( new )
    for c in xrange(5):
        new.children.append( Person() )


def get_nodes(items=[], ages=[], results=[]):
    print "Searching..."
    # pseudo code
    for item in items:
        if item.age in ages:
            print "\t","valid age"
            results.append(item)

        results + get_nodes(items=item.children, ages=ages, results=results)

    return results


AGED_NODES = get_nodes( items=NODES, ages=[2, 4], results=[])
print len(AGED_NODES)
print AGED_NODES
1
  • Wrap it in a non-recursive function A and return the flattened list from A. Commented Dec 2, 2015 at 14:27

1 Answer 1

5

It has always seemed more logical for me that a recursive function like get_nodes should only return its own results - the caller can add on its own results, and the caller's caller does the same. So no I wouldn't pass 'results' into get_nodes.

Also note that your line:

results + get_nodes(items=item.children, ages=ages, results=results)

does nothing.

So my version of your code would look like:

def get_nodes(items=[], ages=[]):
    myresults = []
    print "Searching..."
    # pseudo code
    for item in items:
        if item.age in ages:
            print "\t","valid age"
            myresults.append(item)

        myresults.extend( get_nodes(items=item.children, ages=ages) )

    return myresults
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.