Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest the all function?

Tags:

python

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.

like image 692
forvas Avatar asked Dec 15 '14 13:12

forvas


1 Answers

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
like image 69
Benoît Latinier Avatar answered Oct 02 '22 21:10

Benoît Latinier