[Tutor] fibonacci
Alfred Milgrom
fredm@smartypantsco.com
Wed Feb 12 03:53:01 2003
The solutions presented so far calculate the nth value of the fibonacci
sequence, and certainly Danny Yoo's pseudo-code definition only needs one
(and a bit) additional line to make it work.
However if the sequence is required, rather than the value of the nth
element in the sequence, the following code makes good use of Python's
lists and the ability to index from the end:
def fibonacci(n):
a = [0,1]
if n<3:
return a[:n]
else:
for i in range (2, n):
a.append(a[-1]+a[-2])
return a
print fibonacci(15)
>>> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Just as an exercise, I was unable to create a one-line recursive fibonacci
generator, but the following works correctly for all values of n greater
than 2.
def fib(n):
return (n<5)*(n-2) or fib(n-1) + fib(n-2)
print fib(15)
>>> 377
Fred Milgrom