Preliminary tip: encase your code in [ code="Python ] and [/code] tags (no spaces on the first tag) so that it'll look pretty.
This is a classic case of recursion:
fib(n) = fib(n-1) + fib(n-2)
The best way to compute it is therefore recursively:
>>> def fib(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
This isn't terribly efficient, and perhaps you were supposed to do it with a loop?
Jeff
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
Try looking in the code snippet section of Daniweb to get an idea. There is one in there.
jasimp
Senior Poster
3,623 posts since Aug 2007
Reputation Points: 533
Solved Threads: 53
If you want to access or print all the numbers, append them to a list
test_list = [1, 2] ## Fibs can be started with any 2 numbers
test_list.append( test_list[-1]+test_list[-2] )
print test_list
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
For Python code on Daniweb:
Please use the [code=python] and [/code] tag pair to enclose your python code.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
This is very old thread, if you have questions or want critique of your code, start your own fresh thread. Also the OP of this thread wanted to produce single value for nth fibonacci number. That can be made for example like this:
def fib(n):
prev = [0, 1]
while n>1:
prev = prev[-1], sum(prev)
n -= 1
return prev[n]
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852