是否有内置函数或标准库函数大致等同于
def recur_until(start, step_fu, stop_predicate=lambda _: False):
current = start
while not stop_predicate(current):
yield current
current = step_fu(current)
或
def recur_while(start, step_fu, predicate=lambda _: True):
current = start
while predicate(current):
yield current
current = step_fu(current)
甚至只是
def recur(start, step_fu):
current = start
while True:
yield current
current = step_fu(current)
在任何版本的 Python 中? (当与 itertools.takewhile
结合使用时,后者与其他两个一样好。)
像这样的生成器函数将允许迭代地计算某些递归定义的序列,即一阶递归关系。
虽然这些在需要时实现起来并不难,但我觉得类似的东西应该成为 itertools
or maybe functools
的一部分。 ,但如果是的话,我还没有能够在文档中发现它。
使用示例:
list(recur_until(2, lambda x: x**2 - 1, lambda x: x > 1e4))
# [2, 3, 8, 63, 3968]
也应该与非数字元素一起工作:
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 3.3+ 中,新的 itertools.accumulate
可以与其他 itertools 结合用于此目的
例如:
>>> from itertools import accumulate, repeat, takewhile
>>> fun = accumulate(range(2, 10), lambda x, _: x**2 - 1)
>>> list(fun)
[2, 3, 8, 63, 3968, 15745023, 247905749270528, 61457260521381894004129398783]
>>> fun = takewhile(lambda y: y < 1e4, accumulate(repeat(2), lambda x, _: x**2 - 1))
>>> list(fun)
[2, 3, 8, 63, 3968]
accumulate
接受一个序列和一个带有 2 个参数的函数:第一个是累加值,第二个是序列中的下一个值。在这种情况下,我们只需要第一个参数,它将是传递给 accumulate
的序列的第一个元素,用于传递函数的第一次调用和该函数的返回值用于后续调用。
因此,我们只需要将传递序列的开始作为我们的初始值——在本例中为 2
。序列其余部分的内容无关紧要,但我们可以使用它的长度来控制我们想要的元素数量(如第一个示例)或创建一个无限生成器(如第二个示例)。
关于python - Python是否具有用于一阶递归关系的迭代递归生成器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656810/