Fibonacci - Python - Learning Python
Python入门书籍
Coding Style

Fibonacci - Python

DolaA.M posted @ 2010年10月17日 06:24 in python with tags Fibonacci recursion loop , 1468 阅读

<Python Tutorial>

3.2. First Steps Towards Programming 里 介绍的是 an initial sub-sequence of the Fibonacci series 

 

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print b
...     a, b = b, a+b
...
1
1
2
3
5
8

 

然后在网上扫了下,经过自己的整理弄出下面的代码

 

#!/usr/bin/python
# -*- coding:UTF-8 -*-


#循环算法
def loop(n):
	""" a genertor fo Fibonacci numbers,goes to nex tnumber in series on each call"""

	a,b =0,1
	while a<= 1000:
		print a,
		a,b = b, a+b

#递归算法   
def recursion(n):  
	""" use recursion to get Fibonacci numbers,returns the Fibonacci value for n
		not very efficient because of the many function calls	"""

	if n<2:  
		return n  
	else:  
		return recursion(n-1)+recursion(n-2)  

if __name__=="__main__":
	print "迭代法"
	loop(14)
	print "\n"+'-'*50

	print "递归算法"
	for i in range(17):
		print recursion(i),

用了两种方法,第一个很快,几秒钟就出来了.

用递归的就很慢,特别是n变的很大时,甚至会弄的死机.....你测试一下就知道了~~~~~

 

#!/usr/bin/python
# -*- coding:UTF-8 -*-

#递归算法测试  
def recursion(n):  
	if n<2:  
		return n  
	else:  
		return recursion(n-1)+recursion(n-2)  

for n in range(36):
	print "recursion(%d)=%d"%(n,recursion(n))

print
print "Calculating...."
print

print "recursion(%d)=%d"%(56,recursion(56))
Avatar_small
DolaA.M 说:
2010年10月18日 03:39

???
不太懂,能讲的更 详细点吗

xanpeng 说:
2010年10月18日 08:58

就是把 n-1, n-2 的值存起来


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter