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