
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find length of longest Fibonacci subsequence from a given list in Python
Suppose we have a list of strictly increasing positive numbers called nums. We have to find the length of the longest subsequence A (of length minimum 3) such that A[i] = A[i - 1] + A[i - 2] for all i > 1.
So, if the input is like nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], then the output will be 6, as we can pick [1, 2, 3, 5, 8, 13].
To solve this, we will follow these steps −
- A := nums
- n := size of A
- maxLen := 0
- S := a new set from A
- for i in range 0 to n, do
- for j in range i + 1 to n, do
- x := A[j]
- y := A[i] + A[j]
- length := 2
- while y is present in S, do
- z := x + y
- x := y
- y := z
- length := length + 1
- maxLen := maximum of maxLen, length
- for j in range i + 1 to n, do
- if maxLen > 2, then
- return maxLen
- otherwise,
- return 0
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): A = nums n = len(A) maxLen = 0 S = set(A) for i in range(0, n): for j in range(i + 1, n): x = A[j] y = A[i] + A[j] length = 2 while y in S: z = x + y x = y y = z length += 1 maxLen = max(maxLen, length) if maxLen > 2: return maxLen else: return 0 ob = Solution() nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] print(ob.solve(nums))
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Output
6
- Related Articles
- Program to find length of longest fibonacci subsequence in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Length of Longest Fibonacci Subsequence in C++
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest interval from a list of intervals in Python
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence in C++
- Program to find out the length of longest palindromic subsequence using Python

Advertisements