Alex Rivera | Logout

Fibonacci numbers, with an one-liner in Python 3?

Asked 2011-02-08T17:01:34.370
49

I know there is nothing wrong with writing with proper function structure, but I would like to know how can I find nth fibonacci number with most Pythonic way with a one-line.

I wrote that code, but It didn't seem to me best way:

>>> fib = lambda n:reduce(lambda x, y: (x[0]+x[1], x[0]), [(1,1)]*(n-2))[0]
>>> fib(8)
13

How could it be better and simplier?

Edit
Report

1 Answer

7
fib = lambda n, x=0, y=1 : x if not n else fib(n-1, y, x+y)

run time O(n), fib(0) = 0, fib(1) = 1, fib(2) = 1 ...

answered 2011-04-18T00:25:52.640

Your Answer