[Python] Sequence of function iterations

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a way to abuse assignment expressions or functional tools to generate the sequence x, f(x), f(f(x)), ... in one line?

    Here are some contrived examples to demonstrate:

    def iter(x, f, lim=10):
    for _ in range(lim):
    yield x
    x = f(x)

    iter(1, lambda x: (2*x)%99)


    "One-argument accumulate" is even uglier. The idea is to use the binary function but ignore the list elements!

    from itertools import accumulate
    list(accumulate([None]*10, lambda x,y:2*x, initial=1))

    Continue reading...

Compartilhe esta Página