Functional Style Loop in Python

By Xah Lee. Date: .

Functional Style Loop in Python

# 2024-07-27

# problem:
# write a function
# at_least(n, f, list)
# it return true if list has at least n count where f(ele) is true.


# f is a predicate, it return true or false.
# f is assumed to be very expensive to call.
# the function must be efficient. it must stop going thru the list when n count is found.

# for testing purposes, we assume f is just isEven.
# and assume n is 5

# given
xinput = range(100)

def is_even(n):
    return n % 2 == 0

# HHHH------------------------------

# solution
# using recursive function
# code by Steve

import operator
from functools import reduce
from itertools import accumulate

def at_least(n, f, xlist):
    x = f(xlist[0])
    return x if n - x == 0 else at_least(n - x, f, xlist[1:])
    # WARNING: hack. we are doing arithmetics with boolean


print(at_least(5, is_even, range(100)))

# HHHH------------------------------

# solution 2
# using any, rely on lazy list for efficiency
# code by steve

import operator
from functools import reduce
from itertools import accumulate

def at_least2(n, f, xlist):
    return any(map(lambda x: x >= 5, accumulate(map(is_even, xlist), operator.add)))

print(at_least2(5, is_even, xinput))