sum inside list comprehension

Question:

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.

Asked By: Victor Johnson

||

Answers:

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]]
Answered By: Swifty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.