The problem I am facing is that, given a list and a guard condition, I must verify if every element in the list passes the guard condition.
If even one of the elements fails the guard check, then the function should return false
. If all of them pass the guard check, then the function should return true
. The restriction on this problem is that I can only use a single return statement.
My code:
JavaScript
x
4
1
def todos_lista(lista, guarda):
2
for x in lista:
3
return(False if guarda(x)==False else True)
4
Advertisement
Answer
You should use all:
JavaScript
1
3
1
def todos_lista(lista, guarda):
2
return all(guarda(x) for x in lista)
3
Or in a more functional way:
JavaScript
1
3
1
def todos_lista(lista, guarda):
2
return all(map(guarda, lista))
3
For example for range 0 to 9 (range(10)
):
JavaScript
1
9
1
>>> all(x < 10 for x in range(10))
2
True
3
>>> all(x < 9 for x in range(10))
4
False
5
>>> all(map(lambda x: x < 9, range(10)))
6
False
7
>>> all(map(lambda x: x < 10, range(10)))
8
True
9