简体   繁体   中英

Finding the sum of 3 consecutive numbers in an array

I have to write a function in Python, that prints out the sum of 3 consecutive numbers in an array, for example, if the array has the following values : [10, 20, 30, 40, 50] it should add the first 3 numbers (10 + 20 + 30) and then (20 + 30 + 40) and then (30 + 40 + 50) and so on, until 50 is the last value.

my code to add all the numbers is as follows:

def sum_interval(values, start, stop):
    N = len(values)
    terms = np.zeros(N)

    for i in np.arange(start, stop + 1, 1):
        terms[i] = values[i]

        ans = np.sum(terms)

    return ans

arr = np.array([10, 20, 30, 40, 50])
print(sum_interval(arr, 2, 4))

This following function uses the above mentioned sum_interval definition to compute the summation of the 3 consecutive numbers:

def sum_triplets(values):
    N = len(values)
    terms = np.zeros(N)

    for i in range(0, N, 1):
        terms[i] = sum_interval(values, i, N-1)

    return terms

arr = np.array([10, 20, 30, 40, 50])
print(sum_triplets(arr))

Expected Output: [60, 90, 120, 90, 50]

The Output I get: [150, 140, 120, 90, 50]

If you're already using an array, then you might as well opt for a straightforward NumPy solution. One approach would be to use np.convolve to multiply and sum an array of your desired window size of ones through your input array.

np.convolve(arr, np.ones(3, dtype=np.int), mode='valid')

Demo

>>> arr
array([10, 20, 30, 40, 50])

>>> np.convolve(arr, np.ones(3, dtype=np.int), mode='valid')
array([ 60,  90, 120])

If you're set on using a Python solution, you should avoid the intermediate array storage in your current approach - Willem has you covered with a nice answer in this case.

I do not get why you make it that complicated: you can simply use slicing :

def sum_triplets(values):
    result = []
    for i in range(len(values)):
        result.append(sum(values))
    return result

(boldface added for the slicing part)

You can even put this in a one-liner with list comprehension :

def sum_triplets(values):
    return [sum(values[i:i+3]) for i in range(len(values))]
array = [10, 20, 30, 40, 50]
length = len(array)

n = 0
while n < length:
    m = n
    if m < length:
        first = array[n]
    if m+1 < length:
        second = array[m+1]
    else:
        second = 0
    if m+2 < length:
        third = array[m+2]
    else:
        third = 0
    result = first + second + third
    n = n+1
    print result

In the sum_triplets function, replace the following line:

terms[i] = sum_interval(values, i, N-1)

with

terms[i] = sum_interval(values, i, min(N-1,i+2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM