2

使用赋值表达式,我想我可以尝试列表理解来创建 Fibonacci。我首先初始化一个包含 5 个元素 f = [1,2,3,4,5] 的斐波那契列表,前两个值是种子。下面的测试运行显示了赋值表达式的工作原理。

[y := f[n-1] + f[n-2] for n in range(2,6)] 
[3, 5, 7, 9]

但是真正的斐波那契在 f[n] 处失败,在 Python shell 中显示了一个红色标记。

[f[n] := f[n-1] + f[n-2] for n in range(2,6)] 

是因为 f[n] 不是有效的变量名吗?
这是否意味着赋值表达式可能对斐波那契的列表理解没有帮助?

4

3 回答 3

1

使用[f[n] := ...results in SyntaxError: cannot use assignment expressions with subscript,很明显,这个限制阻止了这样做。这在 PEP 572 中题为“赋值表达式和赋值语句之间的差异”的部分中提到,其中说

  • 不支持单个 NAME 以外的单个分配目标。
于 2020-10-27T06:14:48.347 回答
0

只是为了展示一些我知道的生成 Fibonacci.py 序列的方法:

class   Fib:

    def __init__(self, *f01):
        self.f0, self.f1 = f01

    # Calculate the n-th item of the Fibonacci series
    def fibRecursive(self, n):
        if n == 0:
            return self.f0
        elif n == 1:
            return self.f1
        return self.fibRecursive(n-2) + self.fibRecursive(n-1)

    def fibAppend(self, n):
        f = [self.f0, self.f1]
        for i in range(2, n):
            f.append(f[i-2]+f[i-1])
        return f

    def fibYield(self, n):
        x, y = self.f0, self.f1
        for _ in range(n):
            yield x
            x, y = y, x + y

    def fibIncremental(self, n):
        x, y = self.f0, self.f1
        f = [x, y]
        for i in range(2, n):
            x, y = y, x + y
            f.append(y)
        return f

    def fibLCAE(self, n):   # LC with Assignment expression
        f = [self.f0, self.f1]
        f += [(f := [f[1], f[0] + f[1]]) and f[1] for i in range(2,n)]
        return f

if  __name__ == '__main__':
    n = int(input("How many numbers in the Fibonacci sequence?   "))
    fd = Fib.__dict__
    for f in [Fib(0, 1), Fib(3, -3), Fib(-50, 100)]:
        print(f'Fibonacci initial two numbers : {f.f0}, {f.f1}')
        for func in [fd['fibAppend'], fd['fibIncremental'], fd['fibLCAE']]:
            print(func(f, n))
        print([f.fibRecursive(i) for i in range(n)])
        print(list(f.fibYield(n)))
        print()

>>> python.exe Fibonacci.py
How many numbers in the Fibonacci sequence?   13
Fibonacci initial two numbers : 0, 1
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
....
Fibonacci initial two numbers : 3, -3
[3, -3, 0, -3, -3, -6, -9, -15, -24, -39, -63, -102, -165]
....
Fibonacci initial two numbers : -50, 100
[-50, 100, 50, 150, 200, 350, 550, 900, 1450, 2350, 3800, 6150, 9950]
....
于 2020-11-06T01:00:34.623 回答
0

两个列表推导怎么样,或者建立一个基本列表,然后计算?

生成斐波那契基数组,

fb = [n for n in range(0,21)]
# or
fb = [0] + [1] * 20

计算 fib(13), (想要:[f[n] := f[n-1] + f[n-2] for n in range(2,20)])

f = [ fib(fb,n) for n in range(2,20) ]

其中 fib(f,n) 是:

def fib(f,n):
    if n > 1:
        f[n] = f[n-1] + f[n-2]
    return f[n]

斐波那契数列:

fb[0:13]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
fib(fb,13-1) = 144
于 2020-11-06T01:55:30.433 回答