Your algorithm won't work because you're iterating from index 0 until index len(s)
- 1, excluding the last element since the range
function is end-exclusive (range(0, 5)
iterates from 0 to 4). You can iterate over all elements and introduce a new variable to store the last element:
def sum_consecutives(values):
result = []
# Stores the first consecutive element
last_elem = None
for curr_elem in values:
# If the last element is not initialized,
# initializes it and proceed with the iteration
if last_elem is None:
last_elem = curr_elem
continue
# If the current element is equal to the last
# element, push the sum to the result list
if last_elem == curr_elem:
result.append(last_elem + curr_elem)
# Otherwise, push both elements to the result list
else:
result.append(last_elem)
result.append(curr_elem)
# Reset the last element set
last_elem = None
# If there's an element not paired (i.e. not None),
# push its value to the result array
if last_elem is not None:
result.append(last_elem)
return result
Some tests:
assert sum_consecutives([1, 1, 7, 7, 3]) == [2, 14, 3]
assert sum_consecutives([1]) == [1]
assert sum_consecutives([1, 1]) == [2]
assert sum_consecutives([1, 2, 1]) == [1, 2, 1]
Also, avoid naming your variable sum
, it'll shadow the sum
built-in.