0

I am new to Python and would like to know if recursion works at all. I can't get my code running. It is supposed to print all the the fibonacci numbers:

#!/usr/bin/python
import time, sys

def calc_fib_num(n):
  if (n >= 2):
    return calc_fib_num(n-1) + calc_fib_num(n-2)
  elif (n == 1):
    return 1
  else:
    return 0

print "0",
print "1",

for n in range(2,20):
  fib_num = calc_fib_num(n)
  print fib_num
4

4 回答 4

0

It ran for me, but it took a while. Try lowering the "20" in range(2, 20) to a lower value. I think it's just a performance issue.

于 2013-07-12T21:26:22.230 回答
0

您不需要为此问题导入任何库。试一试。

def fib(n):
    if n == 1:
        return 1
    elif n == 0:
        return 0
    else:
        return fib(n-1) + fib(n-2)

for n in range(2,20):
    print fib(n)
于 2013-07-12T21:33:13.157 回答
0
def fib(n):
    return n if n<2 else fib(n-1) + fib(n-2)

for n in range(2,20):
    print fib(n)
于 2013-07-12T21:59:21.103 回答
0

我可以确认它在 Python 2.7 上对我来说确实有效。我只是将它粘贴到 Python 终端中:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> #!/usr/bin/python
... import time, sys
>>> 
>>> def calc_fib_num(n):
...   if (n >= 2):
...     return calc_fib_num(n-1) + calc_fib_num(n-2)
...   elif (n == 1):
...     return 1
...   else:
...     return 0
... 
>>> print "0",
0
>>> print "1",
1
>>> 
>>> for n in range(2,20):
...   fib_num = calc_fib_num(n)
...   print fib_num
... 
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
>>> 

当然,正如你所说,它不会打印所有的斐波那契数,只是前 20 个。

于 2013-07-12T21:24:29.080 回答