0

to get sum of the sub lists

Hi there, I tried to perform a code which divide the given list into three. And then get sum of each part into a new list (without build in). For example; given list = [1,2,3,4,5,6,7,8,9] output=[6,15,24] My code: def y(x):     t=len(x)     z=0     f=0     sum=[]     if t%3!=0:         return "can not be divided into 3 parts"     else:         for i in range(z,t,int(t/3)):             z=i             r=x[z:z+int(t/3)]             for j in r:                 f=+j             sum.append (f)       return sum y([1,2,3,4,5,6])         i could divide the list into three part. However i can not get the true result for sum of each part. Can anyone help me?

30th Oct 2020, 7:40 PM
Hercule Poirot
Hercule Poirot - avatar
7 Answers
+ 11
Hercule Poirot , nice code. Abhay , you have been faster than me, but i found the same issues. So I have no choice but to improve something else. The code is working with 3 slices in a loop, then calculating the sum of each slice. I thought it would be nice to shorten this by using the sum function: lst = [1,2,3,4,5,6,7,8,9] def y(x): t=len(x) sum_=[] if t%3!=0: return "can not be divided into 3 parts" else: for i in range(0,t,int(t/3)): sum_.append (sum(x[i:i+int(t/3)])) return sum_ print(y(lst))
30th Oct 2020, 8:26 PM
Lothar
Lothar - avatar
+ 3
here it is, def y(x): t=len(x) z=0 f=0 sum=[] if t%3!=0: return "can not be divided into 3 parts" else: for i in range(z,t,int(t/3)): z=i r=x[z:z+int(t/3)] print(r) for j in r: print(j) f+=j sum.append(f) f=0 return sum print(y([1,2,3,4,5,6]))
30th Oct 2020, 8:01 PM
Abhay
Abhay - avatar
+ 3
Hercule Poirot for j in r: Loops over first two numbers and add to f so f has a value of 3 now ,if you won't set f to 0 again it will be keep adding new values from for j in r: loop to 3 so instead of 3,7 you will get 3,10 and so on
30th Oct 2020, 8:14 PM
Abhay
Abhay - avatar
+ 3
ty a lot for your great help. i really appricate it. :)
30th Oct 2020, 8:25 PM
Hercule Poirot
Hercule Poirot - avatar
+ 2
ty a lot Abhay. I m now in phyton and also coding. could you explain what iş the role of f=0 in the code?
30th Oct 2020, 8:10 PM
Hercule Poirot
Hercule Poirot - avatar
+ 2
Lothar nice approach and seems like we don't even need sum variable as well and can use list comprehension instead , lst = [1,2,3,4,5,6,7,8,9] def y(x): t=len(x) if t%3!=0: return "can not be divided into 3 parts" else: return([sum(x[i:i+int(t/3)]) for i in range(0,t,int(t/3))]) print(y(lst))
30th Oct 2020, 8:51 PM
Abhay
Abhay - avatar
+ 1
ty Lothar for your help. :)
30th Oct 2020, 8:38 PM
Hercule Poirot
Hercule Poirot - avatar