Is there a built-in function or a standard library function roughly equivalent
def recur_until(start, step_fu, stop_predicate=lambda _: False): current = start while not stop_predicate(current): yield current current = step_fu(current)
or
def recur_while(start, step_fu, predicate=lambda _: True): current = start while predicate(current): yield current current = step_fu(current)
or even just
def recur(start, step_fu): current = start while True: yield current current = step_fu(current)
in any version of Python? (The latter is as good as the other two in combination with itertools.takewhile .)
Such a generator function will allow iteratively calculated certain recursively defined sequences, namely, first-order repetition relationships.
Although this is not so difficult to implement when necessary, I feel that something like them should be part of itertools or maybe functools , but if so, I have not yet been able to find it in the documentation.
Examples of using:
list(recur_until(2, lambda x: x**2 - 1, lambda x: x > 1e4))
You should also work with elements other than the number:
list(recur_until('', lambda x: '[{}]({})'.format(x, len(x)), lambda x: len(x) > 30)) # ['', # '[](0)', # '[[](0)](5)', # '[[[](0)](5)](10)', # '[[[[](0)](5)](10)](16)', # '[[[[[](0)](5)](10)](16)](22)']
python recursion itertools recurrence functools
das-g
source share