Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created March 25, 2024 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maehrm/0d18184d47db8ca53ae4af1eca7f7a2b to your computer and use it in GitHub Desktop.
Save maehrm/0d18184d47db8ca53ae4af1eca7f7a2b to your computer and use it in GitHub Desktop.
bit演算を使って、冪集合を求めるスクリプト
S = 1 << 1 | 1 << 3 | 1 << 5 # S = {1, 3, 5}
N = 6 # 6ビット使用するため
PS = S # 集合Sの冪集合PSを求める。
ans = [[]] # 空集合は含めておく
while PS > 0:
tmp = []
for i in range(N):
if (PS >> i) & 1:
tmp.append(i)
ans.append(tmp)
PS = (PS - 1) & S # ここの演算が面白い
print(ans)
@maehrm
Copy link
Author

maehrm commented Mar 25, 2024

実行結果

% python power_set.py
[[], [1, 3, 5], [3, 5], [1, 5], [5], [1, 3], [3], [1]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment