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


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

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

To solve this, we will follow these steps −

  • count := 0, ans := 0

  • for i in range 2 to size of nums, do

    • if nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], then

      • count := count + 1

    • otherwise,

      • ans := ans + quotient of (count * (count + 1)) / 2

      • count := 0

  • if count is non-zero, then

    • ans := ans + quotient of (count *(count + 1)) / 2

  • return ans

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, nums):
      count = 0
      ans = 0
      for i in range(2, len(nums)):
         if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
            count += 1
         else:
            ans += (count * (count + 1)) // 2
            count = 0
      if count:
         ans += (count * (count + 1)) // 2
      return ans

ob = Solution()
nums = [6, 8, 10, 12, 13, 14]
print(ob.solve(nums))

Input

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

Output

4

Updated on: 10-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements