Implementing Fibonacci in Python is one of the classical problems you need to master. It can be done in many ways, and we will cover the two main ones here.
Don’t let that stop you to proceed.
Mastering the Fibonacci problem in Python can teach you a lot.
Are you ready for that?
The Fibonacci sequence is as follows.
0 1 1 2 3 5 8 13 21 34 ...
(continues)
It is generated as follows.
The next number is generated by adding the two last numbers.
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
8 + 13 = 21
13 + 21 = 34
21 + 34 = 55
...
Write a program that prints the Fibonacci sequence.
You will do it in two ways in this project.
How to solve this?
Well, the first thought is to make it in an iterative way.
def fib(n):
if n <= 1:
return n
i = 0
j = 1
for _ in range(n):
i, j = j, i + j
return i
You try to follow how the sequence is calculated and this can be done but seems easy to get lost in the code.
To generate the sequence you can run this code.
for i in range(10):
print(fib(i))
The first time you see recursion, it might not be easy to understand.
But after inspecting the following code, you might find it easier to write and follow.
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
This actually generates the same sequence.
The code is actually writing the exact formula for generating it.
You can get the sequence as follows.
for i in range(10):
print(fib(i))
This is part of 19 Python Projects and you can build the classical guess number game and sharpen 6 essential skills.
Build and Deploy an AI App with Python Flask, OpenAI API, and Google Cloud: In…
Python REST APIs with gcloud Serverless In the fast-paced world of application development, building robust…
App Development with Python using Docker Are you an aspiring app developer looking to level…
Why Value-driven Data Science is the Key to Your Success In the world of data…
Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…
Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…