Given this pseudo code of a function
f(0) = 1;
f(1) = 3;
f(n) = 3 * f(n - 1) - f(n - 2); // for n >= 2.
Is there a non recursive way o
Here is simply a function with minimum line of code and maximum flexibility.
You can add any "initial values" and any other recursive "function" you want simply.
def fib(n):
fibs = [1, 3] # <-- your initial values here
if n == 1:
return fibs[0]
if n == 2:
return fibs[:1]
for i in range(2, n):
fibs.append(3*fibs[-1] - fibs[-2]) # <-- your function here
return fibs
And the result is:
n=10
print(fib(n))
[1, 3, 8, 21, 55, 144, 377, 987, 2584, 6765]