Write a python code that checks Fibonacci sequence with explanation.
Write a python code that checks Fibonacci sequence with explanation.
267
23-Apr-2025
Updated on 27-Apr-2025
Khushi Singh
27-Apr-2025A Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It typically starts with 0 and 1. So, the sequence goes like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...Now, if you are given a list and want to check if it forms a Fibonacci sequence, you need to verify that for every element starting from the third one, the rule
list[i] == list[i-1] + list[i-2]holds true.To check this, you can iterate through the list starting from index 2 and validate the condition. If at any point the rule breaks, it is not a Fibonacci sequence.
This logic is simple and efficient, especially for small to medium-sized lists. If the list has fewer than three elements, we can directly say it is a Fibonacci sequence, because there aren't enough numbers to violate the rule.
Below is the Python code to check if a given list follows the Fibonacci sequence:
Explanation of Code:
True.