python实现Fibonacci和二分法

简介:

最简单的实现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


相关文章
Python print() 打印两个 list ,实现中间换行
Python print() 打印两个 list ,实现中间换行
|
Python
Python实现因子分析(附案例实战)
Python实现因子分析(附案例实战)
1055 0
Python实现因子分析(附案例实战)
|
11月前
|
Python
Python 二分法和牛顿迭代法求算术平方根的一点小改进
Python 二分法和牛顿迭代法求算术平方根的一点小改进
56 0
|
JSON 区块链 数据格式
Python实现一个简单的区块链
本文介绍如何用Python实现一个简单的区块链。
485 0
|
存储 数据安全/隐私保护 计算机视觉
python 实现pacs功能 推送下拉影像
python 实现dcmtk关联pacs功能 推送下拉影像
229 0
python 实现pacs功能 推送下拉影像
|
算法 大数据 Python
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
123 2
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
|
前端开发 Python
Leecode加法题目3个 每日练习 Python实现
Leecode加法题目3个 每日练习 Python实现
87 0
Leecode加法题目3个 每日练习 Python实现
|
iOS开发 Python
Python实现微信消息连续发送
Python实现微信消息连续发送
Python实现微信消息连续发送
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
|
Python
Python分分钟实现图书管理系统(含代码)
Python分分钟实现图书管理系统(含代码)
286 0

热门文章

最新文章