Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a function like Mma's NestList in Python

For example : NestList(f,x,3) ----> [x, f(x), f(f(x)), f(f(f(x)))]

http://reference.wolfram.com/mathematica/ref/NestList.html

like image 547
chyanog Avatar asked Oct 17 '25 10:10

chyanog


1 Answers

You could write it as a generator:

def nestList(f,x,c):
    for i in range(c):
        yield x
        x = f(x)
    yield x

import math
print(list(nestList(math.cos, 1.0, 10)))

Or if you want the results as a list, you can append in a loop:

def nestList(f,x,c):
    result = [x]
    for i in range(c):
        x = f(x)
        result.append(x)
    return result

import math
print(nestList(math.cos, 1.0, 10))
like image 114
Mark Byers Avatar answered Oct 20 '25 01:10

Mark Byers