Python中的Power Set生成

时间:2014-09-21 17:29:30

标签: python

我正在尝试生成电源设置并添加powerset的元素。这就是我所做的。

示例:

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

示例I / O:

输入: 1 3

输出:24

我的代码:

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))

我得到了正确的输出,但是计算更大的数字需要更多的时间。

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

如何让它运行得更快。感谢

3 个答案:

答案 0 :(得分:5)

答案很简单:

n * (n + 1) * 2 ** (n - 2)

电源设置中有2 **个元素,每个数字恰好显示在其中一半,因此每个数字显示2 **(n - 1)次。

所以答案是:(1 + 2 + ... + n)* 2 **(n - 1),可以减少到答案的顶部。

很多时候,那些与数学相关的问题不是关于使用残酷的力量,而是先做数学。

答案 1 :(得分:0)

################################################ Power set ########################################################
# The power set of a set is the set of all its subsets, or a collection of all the different combinations of items# 
#                               contained in that given set                                                       #
################################################################################################################### 
# 1) SET,is a collection of any number of unique objects whose order does not matter.                             #
# 2) The subset of a set is any combination (the null set included) of its members,                               #
#    such that it is contained inside the superset                                                                #
# 3) The length, or cardinality, of a power set is 2power(n)                                                      #
########################################### Algorithm #############################################################
# 1) Start with an empty set [] and its power set is []                                                           #
# 2) For every element inside the Set                                                                             #
#     a) Create a copy of every set in the current power-set                                                      #
# 3) Add the element to each one.                                                                                 #
# 4) Add the copies to the current power-set.                                                                     #
###################################################################################################################

import sys

def expand_power_set(set):
  cardinality=2**len(set)
  print("Cardinality of the power set is", cardinality)
  power_set=[[]]
  for element in set:
    # iterate over the sub sets so far
    for subset in power_set:
      # add a new subset consisting of the subset at hand added elem
      power_set=power_set+[list(subset)+[element]]
  return power_set


if __name__ == "__main__":
   #powerset =sys.argv
   #powerset =['a','b','c']
   powerset= [1,2,3]
   output = expand_power_set(powerset)
   print("Expand the power set:", output)

答案 2 :(得分:0)

我添加了一个答案,并附有解释以生成幂集here。因此,有关该功能的详细说明,请转到此处。

def power_set(A):
    length = len(A)
    return {
        frozenset({e for e, b in zip(A, f'{i:{length}b}') if b == '1'})
        for i in range(2 ** length)
    }

现在,您只需运行以下命令即可:

>>> sum(sum(s) for s in power_set(S))
24