繁体   English   中英

Python:无需使用任何内置函数(如itertools等)即可找到幂集

[英]Python : Finding power set without using any inbuilt function like itertools etc

我正在尝试使用位操作找到功率集。我可以生成所有功率集,但它们不可索引。 我无法将其另存为列表列表。 我试图通过Internet找到解决方案,但无法获取相关信息。

这是我使用的代码。

n = int(input()) # Size of the array
noteValue = []   # Array whose power set is to be found
for i in range(n):
    noteValue.append(int(input()))


powerSet = []
for i in range(1<<n):
    for j in range(n):
        if (i & (1<<j) > 0 ):
            powerSet.append(noteValue[j])

print(powerSet)

输出:

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

所需输出:

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

实际上,您可以像以下示例一样使用临时列表sub

powerSet = []
for i in range(1<<n):
    # Add sub list 
    sub = []
    for j in range(n):
        if (i & (1<<j) > 0 ):
            # Append to sub list
            sub.append(noteValue[j])
    # Then append sub to pwerset after finishing the inner loop
    powerSet.append(sub)

print(powerSet)

因此,使用此输入:

2
2
3

它将输出:

[[], [2], [3], [2, 3]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM