A
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:
def is_fibonacci_sequence(seq):
if len(seq) < 3:
return True # A sequence with less than 3 numbers is considered Fibonacci
for i in range(2, len(seq)):
if seq[i] != seq[i-1] + seq[i-2]:
return False
return True
# Example usage
sequence1 = [0, 1, 1, 2, 3, 5, 8]
sequence2 = [2, 5, 7, 12, 19]
print("Sequence 1 is Fibonacci:", is_fibonacci_sequence(sequence1))
print("Sequence 2 is Fibonacci:", is_fibonacci_sequence(sequence2))
Explanation of Code:
If the list has fewer than three elements, return True.
For each number starting from index 2, check if it equals the sum of the two preceding numbers.
If all conditions pass, the list is a
Fibonacci sequence; otherwise, it is not.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A 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.