只是为了展示一些我知道的生成 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]
....