Ai
1 Star 0 Fork 1

jack2583/PythonExamples

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
fibonacci.py 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
pointer-04 提交于 2020-10-03 18:23 +08:00 . Update fibonacci.py
# Fibonacci tool
# This script only works with Python3!
import time
def getFibonacciIterative(n: int) -> int:
"""
Calculate the fibonacci number at position n iteratively
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a
def getFibonacciRecursive(n: int) -> int:
"""
Calculate the fibonacci number at position n recursively
"""
a = 0
b = 1
def step(n: int) -> int:
nonlocal a, b
if n <= 0:
return a
a, b = b, a + b
return step(n - 1)
return step(n)
def getFibonacciDynamic(n: int,fib: list) -> int:
'''
Calculate the fibonacci number at position n using dynamic programming to improve runtime
'''
if n==0 or n==1:
return n
if fib[n]!=-1:
return fib[n]
fib[n]=getFibonacciDynamic(n-1,fib)+getFibonacciDynamic(n-2,fib)
return fib[n]
def main():
n=int(input())
fib=[-1]*n
getFibonacciDynamic(n,fib)
def compareFibonacciCalculators(n: int) -> None:
"""
Interactively compare both fibonacci generators
"""
startI = time.clock()
resultI = getFibonacciIterative(n)
endI = time.clock()
startR = time.clock()
resultR = getFibonacciRecursive(n)
endR = time.clock()
s = "{} calculting {} => {} in {} seconds"
print(s.format(
"Iteratively", n, resultI, endI - startI
))
print(s.format(
"Recursively", n, resultR, endR - startR
))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/jack2583/pythonExamples.git
git@gitee.com:jack2583/pythonExamples.git
jack2583
pythonExamples
PythonExamples
master

搜索帮助