[英]Finding a power spectrum in Python, without using the inbuilt FFT function
[英]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.