ActiveState Code

Recipe 67677: fibonacci


One Liner fibonacci series generator

Python
1
2
3
4
#get nth fibonacci number for n < = 0 returns 1
fib = lambda n,a=1,b=1:n-1 + abs(n-1) and fib(n-1,b,a+b) or b
#another version
fib = lambda n,a=1,b=1:[b,0][n>0] or fib(n-1,b,a+b)

Discussion

get nth fibonacci number for n < = 0 returns 1

Comments

  1. 1. At 7:05 p.m. on 14 feb 2005, Brett Cannon said:

    Differing results. Trying fib(10) on the first version returns 89. But the same Fibonacci number for the second returns 144.

    Also seems off since the second Fibonacci number is 2 when it is supposed to be 1. Seems to lead to the correct value being in the argument + 1.

Sign in to comment