【问题标题】:python - custom power set functionpython - 自定义幂集函数
【发布时间】:2018-11-30 08:39:36
【问题描述】:

我正在尝试在 python 中执行此代码,它编译时没有错误。但是,我在变量资源管理器中看不到变量 z。我正在尝试创建一个函数来提供输入集的所有子集。

import numpy as np
import itertools as itt

def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return itt.chain.from_iterable(itt.combinations(s, r) for r in 
range(len(s)+1))

def powerset_generator(i):
for subset in itt.chain.from_iterable(itt.combinations(i, r) for r in 
range(len(i)+1)):
yield set(subset)

z=powerset({1,2,3})

【问题讨论】:

  • print(list(z))

标签: python powerset


【解决方案1】:

简单的幂集函数

import math 

def powerSet(LIST,SIZE): 
    sizeOfAll = (int) (math.pow(2, SIZE))
    i = 0
    store = 0
    print("Φ")
    for i in range(1, sizeOfAll):
        store = format(i,'0'+str(SIZE)+'b')
        j=0
        for j in range(0,SIZE):
            if store[j] == '1':
                print(LIST[j],end="")
        print()

powerSet(['a', 'b', 'c','d'], 4)

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多