0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

python bit全探索

Last updated at Posted at 2020-05-18

方法1

>>> from itertools import product
>>> n = 3
>>> [[i for i, j in zip(range(n), mask) if j] for mask in product((0, 1), repeat=n)]
[[], [2], [1], [1, 2], [0], [0, 2], [0, 1], [0, 1, 2]]

>>> n = 5
>>> [[i for i, j in zip(range(n), mask) if j] for mask in product((0, 1), repeat=n)]
[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4], [0], [0, 4], [0, 3], [0, 3, 4], [0, 2], [0, 2, 4], [0, 2, 3], [0, 2, 3, 4], [0, 1], [0, 1, 4], [0, 1, 3], [0, 1, 3, 4], [0, 1, 2], [0, 1, 2, 4], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

方法2

>>> n = 3
>>> [[i for i in range(n) if bit & (1<<i)] for bit in range(1<<n)]
[[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2]]

>>> n = 5
>>> [[i for i in range(n) if bit & (1<<i)] for bit in range(1<<n)]
[[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2], [3], [0, 3], [1, 3], [0, 1, 3], [2, 3], [0, 2, 3], [1, 2, 3], [0, 1, 2, 3], [4], [0, 4], [1, 4], [0, 1, 4], [2, 4], [0, 2, 4], [1, 2, 4], [0, 1, 2, 4], [3, 4], [0, 3, 4], [1, 3, 4], [0, 1, 3, 4], [2, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4], [0, 1, 2, 3, 4]]

case: cpp

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

int main() {
  int N = 3;

  map<int, vector<int>> mp;
  rep(bit, (1 << N)) rep(i, N) if (bit & (1 << i)) mp[bit].push_back(i);

  for (auto x : mp) {
    cout << x.first << " : ";
    for (int n : x.second) cout << n << ' ';
    cout << endl;
  }
}
output

1 : 0 
2 : 1 
3 : 0 1 
4 : 2 
5 : 0 2 
6 : 1 2 
7 : 0 1 2 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?