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:
JavaScript
x
2
1
mylist = [2,3,4,10,12,13]
2
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:
JavaScript
1
9
1
mylist = [13,12,10,4,3,2]
2
3
result = mylist[-1] #if I don't do this, I don't know how to grab the last item in the list
4
for i in range(len(mylist)-1):
5
if mylist[i] - mylist[i+1] == 1:
6
continue
7
else:
8
result += mylist[i]
9
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:
JavaScript
1
16
16
1
mylist = [13,12,10,4,3,2]
2
mylist.sort() # this way sequences will be contiguous in the list
3
4
cur_index = 0
5
cur_sum = 0
6
7
while cur_index < len(mylist):
8
# add the current element to the sum
9
cur_sum += mylist[cur_index]
10
# now iterate through while it's a contiguous sequence
11
cur_index += 1
12
while cur_index < len(mylist) and mylist[cur_index] == mylist[cur_index - 1] + 1:
13
cur_index += 1
14
15
print(cur_sum)
16