【问题标题】:Using fibonacci: Python function that halts execution and starts from where it halted使用斐波那契:暂停执行并从它停止的地方开始的 Python 函数
【发布时间】:2020-08-30 15:32:40
【问题描述】:

我想要一个停止的 python 函数,比如在第 150 个数字处,然后当我需要第 400 个数字时,它不会重新计算前 150 个斐波那契数字,它从第 150 个数字开始直到第 400 个数字。

【问题讨论】:

标签: python fibonacci


【解决方案1】:

你可以试试生成器:


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

【讨论】:

  • 生成器方法是我一直在寻找的方法!
【解决方案2】:

我认为您可以实现一个数组来存储所有已计算的数字,无论是在变量中、使用 numpy 的导出数组还是在数据库中,并使其使用最后一个数字。 然后该函数必须采用 startnumber 和 stopnumber 参数。 我不知道你是否可以只计算一个特定的斐波那契数,因为它是一个递归函数。

【讨论】:

  • 这可行,但会影响内存使用。我正在寻找能够解决这个问题的预定义函数。
【解决方案3】:

你可以这样完成:

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 的执行,然后在收到输入响应后继续。

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 2014-05-23
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2013-08-03
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多