I have a list of objects named items. Each object has a property state and a property children, which is another list of objects. And each child object has also a property named state. What I want to know is if every item and their children are in the states happy or cheerful.
I did this with all (only analysing the states of the items):
if all(item.state in ['happy', 'cheerful'] for item in items):
pass
I would like to know which is the best way to do the same with not only items but children too.
You are seeking for some recursion here:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items)
As @tobias_k pointed out this should be quicker since it iterates only once on items:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items)
It is at least more readable.
In the case you only have two layers of objects a simple for might do the trick too.
def is_happy(items):
happy_children = True
for item in items:
if any(child.state not in ['happy', 'cheerful'] for child in item):
happy_children = False
break
return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With