Welcome, guest | Sign In | My Account | Store | Cart

One Liner fibonacci series generator

Python, 4 lines
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)

get nth fibonacci number for n < = 0 returns 1

1 comment

Brett Cannon 19 years, 2 months ago  # | flag

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.

Created by anurag uniyal on Thu, 30 Aug 2001 (PSF)
Python recipes (4591)
anurag uniyal's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks