Search code examples
pythonlistsequences

Arithmetic Sequences Slices in Python


I'm trying to write a function that takes a list of integers and finds all arithmetic sequences in it.

A = [-1, 1, 3, 3, 3, 2, 1, 0]

There are five arithmetic sequences in this list: (0, 2), (2,4), (4, 6), (4,7), (5,7) - these are indexes of first and last element of a sequence. A sequence is derived by the difference between elements.

As you see from the example above - the sequence must be longer than 2 elements (otherwise it would find a sequence between every two elements).

The function that I need to write must return the number of sequences it finds on the list - in this case it should return 5.

I'm kind of stuck - tried a few different approaches but failed miserably. The most recent thing I've done is:

def solution(A):
slices = []
x = 0
listlen = len(A)
while x < listlen-1:
    print ("Current x:", x)
    difference = A[x+1] - A[x]
    #print ("1st diff: ", A[x+1], ",", A[x], " = ", difference)
    for y in range(x+1, len(A)-1):
        difference_2 = A[y+1] - A[y]
        #print ("Next Items: ", A[y+1], A[y])
        #print ("2nd diff: ", difference_2)
        if (difference == difference_2):
            #print ("I'm in a sequence, first element at index", x)
        else:
            #print ("I'm leaving a sequence, last element at index ", y)
            slice = str(x) + "," + str(y)
            slices.append(slice)
            x += 1
            #print ("Changing X to find new slice: x:", x)
            break
print (slices)

I messed something up with iterating X, at this point in time, it's an endless loop.


Solution

  • Maybe you can use a logic like this -

    >>> A = [-1, 1, 3, 3, 3, 2, 1, 0]
    >>> def indices(l):
    ...     res = []
    ...     for i in range(0,len(l)-2):
    ...             diff = l[i+1] - l[i]
    ...             for j in range(i+2,len(l)):
    ...                     if (l[j] - l[j-1]) == diff:
    ...                             res.append((i,j))
    ...                     else:
    ...                             break;
    ...     return res
    ...
    >>> indices(A)
    [(0, 2), (2, 4), (4, 6), (4, 7), (5, 7)]