-2

I'm trying to calculate the numbers of the fibonacci Sequence under 100, but the code I made doesn't work. What I have is:

def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
num=0
while(num<100):
        print (fib(num))
        num+=1

I think this should work, but it doesn't, so it's definitely my issue with my coding. Could anyone resolve this?

Xymostech
  • 9,380
  • 3
  • 33
  • 44
waco001
  • 61
  • 1
  • 2
  • 10
  • 1
    Duplicate of [this posting](http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python?rq=1)? – bbayles Apr 14 '13 at 00:30
  • 4
    When you post a question *'it doesn't work'* isn't very helpful. Explain **how** it doesn't work. Note that using a `while` loop to loop over a range of numbers isn't particularly pythonic - consider [the `range` function](http://docs.python.org/3.3/library/functions.html#func-range) instead (or [`xrange()` in 2.x](http://docs.python.org/2.7/library/functions.html#xrange)). – Gareth Latty Apr 14 '13 at 00:33
  • I see my mistake. I was counting the number of calculations, not the number of digits. – waco001 Apr 14 '13 at 00:35
  • Seems to work fine on my computer. Whats the problem? – Blair Apr 14 '13 at 01:01
  • There's no problem with this code except that it's inefficient for finding the Fibonacci *sequence* - should use a generator – Jared Apr 14 '13 at 01:05
  • Your code is correct. Maybe you should have looked up the first 100 fibonacci numbers before arguing the validity of your results – erdekhayser Apr 14 '13 at 00:40

1 Answers1

1

So what about this code is not working? It looks like the implementation is correct, but it's of course, slow. You can try to store the numbers you compute in some kind of data structure as you go along to reduce your stack trace and prevent having to recalculate fib of 23 when you're trying to calculate fib of 24.

sahhhm
  • 5,235
  • 2
  • 26
  • 22