Skip to content
Advertisement

Sum of lowest numbers that are part of an arithmetic sequence

I would like to iterate through a list of integers, calculate the sum of the lowest numbers that belongs to an arithmetic sequence with common difference 1 + the numbers that are not part of a sequence:

mylist = [2,3,4,10,12,13]

So, from mylist it would be 2 (from 2,3,4) + 10 (not part of a sequence) + 12 (from 12,13)

I’ve managed to make something work, but I could only figure out how to do it, if the list is reversed. And I am sure there is a better/cleaner solution that mine:

mylist = [13,12,10,4,3,2]

result = mylist[-1] #if I don't do this, I don't know how to grab the last item in the list
for i in range(len(mylist)-1):
    if mylist[i] - mylist[i+1] == 1:
        continue
    else:
        result += mylist[i]

Hope someone will help me out, and that I get a little wiser in my coding journey. Thanks.

Advertisement

Answer

Keep a running sum, a running index, and iterate while it’s still a sequence:

mylist = [13,12,10,4,3,2]
mylist.sort() # this way sequences will be contiguous in the list

cur_index = 0
cur_sum = 0

while cur_index < len(mylist):
    # add the current element to the sum
    cur_sum += mylist[cur_index]
    # now iterate through while it's a contiguous sequence
    cur_index += 1
    while cur_index < len(mylist) and mylist[cur_index] == mylist[cur_index - 1] + 1:
        cur_index += 1

print(cur_sum)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement