📅  最后修改于: 2023-12-03 14:52:30.280000             🧑  作者: Mango
斐波那契数列是一个无限序列,该序列中的每个项都是前两个项的和。常见的斐波那契数列的前几个数字是:0, 1, 1, 2, 3, 5, 8, 13, ...
以下是在 Python 中创建斐波那契数列的几种常见方法:
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
n = 10
fib_sequence = fibonacci(n)
print(fib_sequence)
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
n = 10
fib_sequence = []
for i in range(n):
fib_sequence.append(fibonacci(i))
print(fib_sequence)
def fibonacci_generator():
a, b = 0, 1
yield a
yield b
while True:
a, b = b, a + b
yield b
n = 10
fib_sequence_generator = fibonacci_generator()
fib_sequence = [next(fib_sequence_generator) for _ in range(n)]
print(fib_sequence)
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(0)
for i in range(2, n):
fib[i] = fib[i-1] + fib[i-2]
return fib
n = 10
fib_sequence = fibonacci(n)
print(fib_sequence)
以上介绍了在 Python 中创建斐波那契数列的几种常见方法,包括使用循环、递归、生成器和动态规划。选择合适的方法取决于具体的应用场景和性能需求。希望这篇介绍能帮助你理解如何在 Python 中创建斐波那契数列。