Here is my suggestion with one function for the sum and one function for the fraction, given the width of the list and window. It does not use an external package and is rather short, easy to read and understand:
def sumWithWindow(aList, window = 2):
res = []
mySum = 0
for i,elem in enumerate(aList):
mySum += elem
if (i+1) % window == 0:
res.append(mySum)
mySum = 0
return (res)
def fractionWithWindow(aList, window = 2):
res = []
b = sumWithWindow(aList, window)
for i,elem in enumerate(aList):
res.append(elem/b[int(i/window)])
return (res)
a = [10, 20, 30 , 40, 50 , 60]
print(sumWithWindow(a, 2))
print(fractionWithWindow(a,2))
A single-layer version with a list is also available here, a little less clear, but very short:
def sumWithWindow(aList, window = 2):
return [sum(aList[n:n+window]) for n in range(0,len(aList),window)]
def fractionWithWindow(aList, window = 2):
return [elem/sumWithWindow(aList,window)[i//window] for i,elem in enumerate(aList)]
a = [10, 20, 30 , 40, 50 , 60]
print(sumWithWindow(a, 2))
print(fractionWithWindow(a,2))
source
share