[英]Python : Finding power set without using any inbuilt function like itertools etc
I am trying to find the power set using bit manipulation.I can generate all sets but they are not indexable. 我正在尝试使用位操作找到功率集。我可以生成所有功率集,但它们不可索引。 I could not save it as a list of list.
我无法将其另存为列表列表。 I tried to find the solution over the internet but could not get the relevant information.
我试图通过Internet找到解决方案,但无法获取相关信息。
Here is the code I used. 这是我使用的代码。
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)
Output: 输出:
[1, 2, 1, 2, 3, 1, 3, 2, 3, 1, 2, 3]
Desired Output: 所需输出:
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Actually you can use a temporary list sub
like this example: 实际上,您可以像以下示例一样使用临时列表
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)
So, with this input: 因此,使用此输入:
2
2
3
It will output: 它将输出:
[[], [2], [3], [2, 3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.