python自定义幂函数

2024-05-12 21:58:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用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})

Tags: 代码infromimportchainforlendef
1条回答
网友
1楼 · 发布于 2024-05-12 21:58:53

简单的Powerset函数

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)

相关问题 更多 >