Reputation:
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]
Upvotes: 2
Views: 4033
Reputation: 4233
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
Upvotes: -1
Reputation: 2111
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))
Upvotes: -2
Reputation: 29680
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.
Upvotes: 6
Reputation: 476557
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[i:i+3]))
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))]
Upvotes: 3