最简单的实现Fabonacci代码:
def Fibonacci(n):
if n <= 1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
我们可以用一个数组存储,牺牲空间换取时间,避免多次无效求值
代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->代码
list = [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def Fibonacci(n):
if list[n] != 0:
return list[n]
else:
list[n] = Fibonacci(n-1) + Fibonacci(n-2)
return list[n]
二分法
代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->def BinarySearch(numbers,x,n):
left = 0;right = n - 1
while(left <= right):
middle = (left + right)/2
if numbers[middle] == x:
return middle + 1
elif numbers[middle] > x:
right = middle-1
else:
left = middle + 1
else:
return -1