📅  最后修改于: 2023-12-03 14:41:11.144000             🧑  作者: Mango
Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence has applications in math, science, and even art. In this article, we will explore how to generate Fibonacci sequence in Python.
One of the simplest ways to generate Fibonacci sequence is by using recursion. In this approach, we define a function that calls itself recursively to compute the next number in the sequence.
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
# Generate first 10 numbers in the Fibonacci sequence
for i in range(10):
print(fib(i))
Output:
0
1
1
2
3
5
8
13
21
34
Another way to generate Fibonacci sequence is by using iteration. In this approach, we use a for loop to iterate over a range of numbers and compute the next number in the sequence.
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# Generate first 10 numbers in the Fibonacci sequence
for i in range(10):
print(fib(i))
Output:
0
1
1
2
3
5
8
13
21
34
Memoization is an optimization technique that involves caching the results of function calls and returning the cached result when the same input occurs again. This can be used to optimize recursive functions like the one we used in Method 1 to generate the Fibonacci sequence.
memo = {0: 0, 1: 1}
def fib(n):
if n not in memo:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
# Generate first 10 numbers in the Fibonacci sequence
for i in range(10):
print(fib(i))
Output:
0
1
1
2
3
5
8
13
21
34
In conclusion, there are multiple ways to generate Fibonacci sequence in Python. We explored three methods: using recursion, using iteration, and using memoization. Choose the method that best suits your needs and enjoy generating Fibonacci sequences in Python!