-1

Hello there i'm trying sum_consecutives as the function name mention in array example:

[1,1,7,7,3] should return [2,14,3]

Problem: Looks like my algorithm not working with all the array i get this result everytime [2,14]

the function:

def sum_consecutives(s):

    sum = 0
    X = []
    for i in range(0,len(s)-1):
        print( i)
        if s[i] == s[i+1]:
            sum += s[i]
        else:
            X.append(sum+s[i])
            sum = 0
      
    return X
TigerTN
  • 41
  • 7
  • Does this answer your question? [adding two consecutive numbers in a list](https://stackoverflow.com/questions/9161525/adding-two-consecutive-numbers-in-a-list) – Nikolaos Chatzis Oct 16 '21 at 23:18
  • 1
    @NikolaosChatzis That one isn't about adding *equal* numbers. This question here, judging by their code, wants `[sum(g) for _, g in groupby(s)]`. – no comment Oct 16 '21 at 23:49

1 Answers1

2

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.

enzo
  • 9,861
  • 3
  • 15
  • 38