Python 它将构建字典缓存,直到try语句工作,一旦try语句工作,它将返回结果并完成…print语句如何工作?如果FibonacciStorage.\u fib(1号)正在被立即调用?或者是否存在延迟(在执行递归之前是否等待函数结束)?抱歉,这是我感到困惑的地方.
Python 它将构建字典缓存,直到try语句工作,一旦try语句工作,它将返回结果并完成…print语句如何工作?如果FibonacciStorage.\u fib(1号)正在被立即调用?或者是否存在延迟(在执行递归之前是否等待函数结束)?抱歉,这是我感到困惑的地方.,python,algorithm,Python,Algorithm,它将构建字典缓存,直到try语句工作,一旦try语句工作,它将返回结果并完成…print语句如何工作?如果FibonacciStorage.\u fib(1号)正在被立即调用?或者是否存在延迟(在执行递归之前是否等待函数结束)?抱歉,这是我感到困惑的地方..只要值不在缓存中,就会在添加后立即调用print语句。我认为你应该跟踪程序的执行情况,以便更好地理解它,使用调试器。好的。以前从未这样做过,但我会查找跟踪。谢谢奥斯卡。 # Fibonacci recursive with result st
它将构建字典缓存,直到try语句工作,一旦try语句工作,它将返回结果并完成…print语句如何工作?如果FibonacciStorage.\u fib(1号)正在被立即调用?或者是否存在延迟(在执行递归之前是否等待函数结束)?抱歉,这是我感到困惑的地方..只要值不在缓存中,就会在添加后立即调用print语句。我认为你应该跟踪程序的执行情况,以便更好地理解它,使用调试器。好的。以前从未这样做过,但我会查找跟踪。谢谢奥斯卡。
# Fibonacci recursive with result storage
class FibonacciStorage:
_storage = { 0:1, 1:1 }
@staticmethod
def _fib(number):
try: # is this already calculated
return FibonacciStorage._storage[number] #searches dict, and if value exists then return it
except KeyError:
result = FibonacciStorage._fib(number-1) + FibonacciStorage._fib(number-2) #this is the actual Fibonacci Formula
FibonacciStorage._storage[number] = result #adds result to dictionary
#print FibonacciStorage._storage #this shows the storage list growing with each iteration.
return result
@staticmethod
def fib(number): #first function, it has two asserts to basically make sure number is whole/positive and if its okay passes it to _fib(where the real work is done)
# only do the assert statements once
assert(isinstance(number,int)),"Needs a whole number"
assert(number>0),"Needs a positive whole number"
return FibonacciStorage._fib(number)
# use a more readable name
getFib = FibonacciStorage.fib
print getFib(50)
result = FibonacciStorage._fib(number-1) + FibonacciStorage._fib(number-2)
// here ^ and here ^
fib(4)
/ \
fib(3) + fib(2)
/ \ / \
fib(2) + fib(1) fib(1) + fib(0)
/ \
fib(1) + fib(0)
class FibonacciStorage(dict):
def __missing__(self, n):
self[n] = self[n - 1] + self[n - 2]
return self[n]
fib = FibonacciStorage({0: 1, 1: 1})
print(fib[50]) #20365011074