So I am working on algorithms and I have this section where I can't figure out. Given a list of numbers, get the sum of consecutive values over 0 and add to new list. Expected result:
[1, 2, 3, 0, 1, 1, 1, 0, 2, 2, 2] == [6, 3, 6]
I have tried:
for i in splitlist2:
if i == 0:
resultlist.append((count2))
count2 = 0
else:
count2 = i
Produces [6, 3]. I don't get why the last value is not appearing. Can someone please explain?
CodePudding user response:
def custom_sum(arr):
if not arr: return []
res = [0]
for i, el in enumerate(arr):
if el == 0:
if i != len(arr)-1:
res.append(0)
else:
res[-1] = el
return res
A quick test:
arr = [1, 2, 3, 0, 1, 1, 1, 0, 2, 2, 2]
custom_sum(arr)
[6, 3, 6]
The general algorithm:
- If the input array is empty return empty array
- Otherwise initialize a result array with a 0
- Loop over the elements of the input array:
- If the element is 0, check whether it's the last element. If it's the last element of the input array, ignore. Otherwise, add a zero to the result array for a new partition.
- If the element is not zero, add its value to the last value in result array.
CodePudding user response:
from itertools import groupby
list1 = [1, 2, 3, 0, 1, 1, 1, 0, 2, 2, 2]
ans = []
arr = [list(v) for k,v in groupby(list1, key = lambda x: x != 0) if k != 0]
for i in arr:
ans.append(sum(i))
print(ans)
Output :
[6,3,6]