
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Arithmetic Subsequence in Python
Suppose we have a list of numbers nums and another value diff, we have to find the length of the longest arithmetic subsequence where the difference between any consecutive numbers in the subsequence is same as diff.
So, if the input is like nums = [-1, 1, 4, 7, 2, 10] diff = 3, then the output will be 4, because, we can pick the subsequence like [1, 4, 7, 10].
To solve this, we will follow these steps −
- seen := an empty dictionary, default value is 0 when key is not present
- mx := 0
- for each x in nums, do
- if x - diff is in seen, then
- seen[x] := seen[x - diff] + 1
- otherwise,
- seen[x] := 1
- mx := maximum of mx and seen[x]
- if x - diff is in seen, then
- return mx
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def solve(nums, diff): seen = defaultdict(int) mx = 0 for x in nums: if x - diff in seen: seen[x] = seen[x - diff] + 1 else: seen[x] = 1 mx = max(mx, seen[x]) return mx nums = [-1, 1, 4, 7, 2, 10] diff = 3 print(solve(nums, diff))
Input
[-1, 1, 4, 7, 2, 10], 3
Output
4
Advertisements