【问题标题】:Generates the power set of the set without using pre-defined library?在不使用预定义库的情况下生成集合的幂集?
【发布时间】:2021-09-27 13:36:24
【问题描述】:

我正在尝试生成列表的幂集,而不使用任何库。 例如,给定set {1, 2, 3},,它应该返回{{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}

注意:我们也可以使用列表。

我已经实现了代码,但它不是动态的,它是针对特定长度的。我怎样才能使它动态化。

代码:

my_list = [0, 1, 2, 3]

first_list = []
second_list = [[]]
final_list = []

for iterate in my_list:
    second_list.append([iterate])
    
for outer_loop in my_list:
    for inner_loop in my_list:
        if outer_loop!=inner_loop:
            first_list.append([outer_loop, inner_loop])
            
result = (second_list + first_list)

for iterated in result:
    if sorted(iterated) not in final_list:
        final_list.append(iterated)
final_list + [my_list]

【问题讨论】:

    标签: python list set


    【解决方案1】:

    试试这个:

    def get_powerset(s):
        x = len(s)
        subsets = []
        for i in range(1 << x):
            subsets.append([s[j] for j in range(x) if (i & (1 << j))])
    
        return subsets
    
    lists = [[1, 2, 3], [0, 1, 2, 3]]
    for num_list in lists:
        print(get_powerset(num_list))
    

    输出:

    [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    [[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2], [3], [0, 3], [1, 3], [0, 1, 3], [2, 3], [0, 2, 3], [1, 2, 3], [0, 1, 2, 3]]
    

    【讨论】:

      【解决方案2】:

      除了@Sabil 的回答,递归的方法:

      def get_powerset(s):
          if len(s) == 0: 
              return []
          if len(s) == 1: 
              return [s] 
          without_s0 = get_powerset(s[1:])
          with_s0 = [subs + [s[0]] for subs in without_s0]
          return with_s0 + without_s0
      

      此解决方案采用 item 方法,但可以轻松放宽。

      【讨论】:

        猜你喜欢
        • 2013-07-28
        • 1970-01-01
        • 1970-01-01
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 2021-09-02
        相关资源
        最近更新 更多