I am trying to generate power sets and add up the elements of the powerset. This is what i have done.
Example:
Given N=3,
S={1,2,3}
P(S) = {{1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}
answer = (1)+(2)+(3)+(1+2)+(1+3)+(2+3)+(1+2+3)
= 24
Sample I/O:
Input: 1 3
Output: 24
My code:
from itertools import combinations, chain
j = int(input())
for z in range(j):
x = int(input())
a_set = set()
for m in range(x):
a_set.add(m + 1)
lst = []
for q in chain.from_iterable(combinations(a_set, r) for r in range(len(a_set) + 1)):
lst.append(sum(q))
print(sum(lst))
I am getting the correct output but it takes more time to compute for larger numbers.
Input
First line has T, the total number of test cases.
The next T lines contains a number N in each line.
Output
T lines giving answer as defined in the question for each N.
Constraints
1<=T<=42
1<=N<=42
How to make it run faster. Thanks