Function:
def comulative_sum(arr):
arr1 = []
for number in range(1, len(arr)):
sum1 = 0
for number1 in range(0, arr[number]):
sum1 = number1
arr1.append(sum1)
return arr1
arr = [1, 2, 3, 4]
print(comulative_sum(arr))
Output:
[3, 6, 10]
Expected output:
[1, 3, 6, 10]
I have tried slicing ([1:], [0:number) instead of the range function. Still no results.
CodePudding user response:
The better way to write this function is simply using itertools.accumulate() which does exactly that:
>>> import itertools
>>> print(list(itertools.accumulate([1,2,3,4]))
[1, 3, 6, 10]
CodePudding user response:
you dont need to loop it twice
def cum_sum(x):
result = []
current_sum = 0
for value in x:
current_sum = value
result.append(current_sum)
return result
CodePudding user response:
Multiple issues:
- On the first loop you need to range until
len() 1as the last number islen()and then the last number in second loop will belen() - 1which is also the index. - On the second loop, instead of ranging until
number, you range until the original number in the array.
Fixed code:
def comulative_sum(arr):
arr1 = []
for number in range(1, len(arr) 1):
sum1 = 0
for number1 in range(0, number):
sum1 = arr[number1]
arr1.append(sum1)
return arr1
arr = [1, 2, 3, 4]
print(comulative_sum(arr))
If you wish to improve upon this code and not use a built-in accumulate, you can do so:
def comulative_sum(input_list):
output = []
sum_ = 0 # The underscore is to avoid renaming the built-in sum()
for i in input_list:
sum_ = i
output.append(sum_)
return output
input_list = [1, 2, 3, 4]
print(comulative_sum(input_list))
Advantages:
- Better variable naming.
- Less code nesting.
- Easier overall code readability.
- Faster code (no need to recalculate everything on each iteration)
CodePudding user response:
I built in your solution. This version relies on Python's loop through indexes and also addresses a possible number '0'.
def cumulative_sum(arr):
arr1 = []
# Python does the hard work for you, it loops through each value on the list
for value in arr:
sum1 = 0
# Range is going to have a list as follows [0, ... , value-1]
for number1 in range(0, value):
sum1 = number1
# Adding 'value' to sum1 because the loop did not add the last value
arr1.append(sum1 value)
return arr1
arr = [1, 3, 6, 10]
# Calling the function with 'print' to make sure the results are displayed
print(cumulative_sum(arr))
CodePudding user response:
The for loop will only deal with numbers from index 1 to the end of the array. Thus index 0 will be ignored.
Working function:
def comulative_sum(arr):
arr1 = []
for number in arr[:len(arr)]:
sum1 = 0
for number1 in arr[0:number]:
sum1 = number1
arr1.append(sum1)
return arr1
arr = [1, 2, 3, 4]
print(comulative_sum(arr))
All that was changed was the indexing in the first and second for loop.
