[Tutor] fibonacci

Scott Widney SWidney@ci.las-vegas.nv.us
Wed Feb 12 17:19:24 2003


> I have cut it from the activepython help, because of its beauty:
> 
> # Fibonacci numbers module
> 
> def fib(n):    # write Fibonacci series up to n
>     a, b = 0, 1
>     while b < n:
>         print b,
>         a, b = b, a+b
> 
> def fib2(n): # return Fibonacci series up to n
>     result = []
>     a, b = 0, 1
>     while b < n:
>         result.append(b)
>         a, b = b, a+b
>     return result
> 

And if you want to see the first n items in the 
list of fibonacci numbers:

>>> def fib3(index):
...     result = []
...     a, b = 0, 1
...     while len(result) < index:
...         result.append(b)
...         a, b = b, a+b
...     return result
...
>>> fib3(10)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fib3(20)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610, 987, 1597, 2584, 4181, 6765]
>>>


Regards,
Scott