使用 fibonacci: Python 停止执行并从停止处开始的函数
Using fibonacci: Python function that halts execution and starts from where it halted
我想要一个 python 函数停止,比如说在第 150 个数字然后当我需要第 400 个数字时,它不会重新计算前 150 个斐波那契数字,它从第 150 个数字开始直到第 400 个数.
我认为您可以实现一个数组来存储所有已计算的数字,例如,可以在变量、使用 numpy 的导出数组或在数据库中,并使其使用最后一个数字。
然后该函数必须采用 startnumber 和 stopnumber 参数。
我不知道你是否可以计算一个特定的斐波那契数,因为它是一个递归函数。
你可以试试生成器:
def fibo_gen(a=0,b=1):
while True:
#returns a generator object
yield a
a,b = b, a+b
# create generator object
gen_f = fibo_gen()
fibo_list = [next(gen_f) for i in range(150)]
# get the 151 number without recalculating the previous
next(gen_f)
# will return
9969216677189303386214405760200
或者另一种方法可以使用全局字典:
#fibonacci dict with cached values
fib_cached = {}
def _fib(n):
# check if fibo number is already cached
if n in fib_cached:
return fib_cached[n]
if n<=2:
value=1
else:
value = _fib(n-1) + _fib(n-2)
# save the fibo number to dict
fib_cached[n]=value
return value
您可以这样完成:
def Fibonacci(n, pause_val):
a = 0
b = 1
i = 2
print(a)
print(b)
while i<n:
c = b
b = b + a
a = c
print(b)
i += 1
if i == pause_val:
input('Press Enter to continue: ')
continue
Fibonnaci(400, 150)
你会注意到我在这里使用 input
函数来暂停 Fibonnaci
的执行,然后在收到输入响应后继续。
我想要一个 python 函数停止,比如说在第 150 个数字然后当我需要第 400 个数字时,它不会重新计算前 150 个斐波那契数字,它从第 150 个数字开始直到第 400 个数.
我认为您可以实现一个数组来存储所有已计算的数字,例如,可以在变量、使用 numpy 的导出数组或在数据库中,并使其使用最后一个数字。 然后该函数必须采用 startnumber 和 stopnumber 参数。 我不知道你是否可以计算一个特定的斐波那契数,因为它是一个递归函数。
你可以试试生成器:
def fibo_gen(a=0,b=1):
while True:
#returns a generator object
yield a
a,b = b, a+b
# create generator object
gen_f = fibo_gen()
fibo_list = [next(gen_f) for i in range(150)]
# get the 151 number without recalculating the previous
next(gen_f)
# will return
9969216677189303386214405760200
或者另一种方法可以使用全局字典:
#fibonacci dict with cached values
fib_cached = {}
def _fib(n):
# check if fibo number is already cached
if n in fib_cached:
return fib_cached[n]
if n<=2:
value=1
else:
value = _fib(n-1) + _fib(n-2)
# save the fibo number to dict
fib_cached[n]=value
return value
您可以这样完成:
def Fibonacci(n, pause_val):
a = 0
b = 1
i = 2
print(a)
print(b)
while i<n:
c = b
b = b + a
a = c
print(b)
i += 1
if i == pause_val:
input('Press Enter to continue: ')
continue
Fibonnaci(400, 150)
你会注意到我在这里使用 input
函数来暂停 Fibonnaci
的执行,然后在收到输入响应后继续。