Home > Software design >  sum inside list comprehension
sum inside list comprehension

Time:10-30

I have a list comprehension operation like below:

a = [1,2,15]
def tt(n):
 if n < 1:
  return [[]]
 st= tt(n-1)
 return [row   [v*a[n-1]] for row  in st for v in [0,1]]

tt(3)

I am trying to get sum of each sub list rather than the list.

I currently get :

[[0, 0, 0],  
[0, 0, 15],  
[0, 2, 0],  
[0, 2, 15],  
[1, 0, 0],  
[1, 0, 15],  
[1, 2, 0],  
[1, 2, 15]]

I tried:

a = [1,2,15]
def tt(n):
 if n < 1:
  return [[]]
 st= tt(n-1)
 return [row   [sum([v*a[n-1]])] for row  in st for v in [0,1]]

tt(3)

Expected: [0,15,2,17,1,3,18]

My final aim is to run tt(40) or above.

CodePudding user response:

Here's a modified version of your code (but Daniel Hao's suggestion remains valid).

a = [1,2,15]
def tt(n):
 if n < 1:
  return [0]
 st= tt(n-1)
 return [row   v*a[n-1] for row  in st for v in [0,1]]
  • Related