- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find number of arithmetic subsequences from a list of numbers in Python?

Suppose we have a list of numbers called nums, we have to find the number of arithmetic subsequences of length ≥ 3. As we know an arithmetic sequence is a list of numbers where the difference between one number and the next is the same.

So, if the input is like nums = [6, 12, 13, 8, 10, 14], then the output will be 3, as we have subsequences like: [6, 8, 10], [6, 10, 14], [12, 13, 14].

To solve this, we will follow these steps:

dp := a new map

n := size of nums

res := 0

for i in range 0 to n, do

for j in range 0 to i, do

diff := nums[i] - nums[j]

prev := dp[(i, diff)] if that is not present, then 0

prevprev := dp[(j, diff)] if that is not present, then 0

dp[i, diff] := prev + prevprev + 1

res := res + prevprev

return res

## Example

class Solution: def solve(self, nums): dp = {} n = len(nums) res = 0 for i in range(n): for j in range(i): diff = nums[i] - nums[j] prev = dp.get((i, diff), 0) prevprev = dp.get((j, diff), 0) dp[(i, diff)] = prev + prevprev + 1 res += prevprev return res ob = Solution() nums = [6, 12, 13, 8, 10, 14] print(ob.solve(nums))

## Input

[6, 12, 13, 8, 10, 14]

## Output

3

Advertisements