Skip to content
Advertisement

Guard clause on lists using only functional programming

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:

def todos_lista(lista, guarda):
  for x in lista:
    return(False if guarda(x)==False else True)

Advertisement

Answer

You should use all:

def todos_lista(lista, guarda):
    return all(guarda(x) for x in lista)

Or in a more functional way:

def todos_lista(lista, guarda):
    return all(map(guarda, lista))

For example for range 0 to 9 (range(10)):

>>> all(x < 10 for x in range(10))
True
>>> all(x < 9 for x in range(10))
False
>>> all(map(lambda x: x < 9, range(10)))
False
>>> all(map(lambda x: x < 10, range(10)))
True
Advertisement