Learning Python

Fibonacci - Python

<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))