Wpis z mikrobloga

Co robi to "if (i >> j) % 2 == 1" w generatorze? Czemu tam musi być ">>"?

def powerSet(items):
    N = len(items)
    
# enumerate the 2**N possible combinations
    for i in xrange(2**N):
        combo = []
        for j in xrange(N):
            
# test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

#python
  • 8
@rybycy: @Sarpens: Dzięki, mniej więcej zrozumiałem o czym mówicie po puszczeniu:

def powerSet(items):
    N = len(items)
    
# enumerate the 2**N possible combinations
    for i in xrange(2**N):
        combo = []
        for j in xrange(N):
            
# test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
            print i, j, bin(i), i >> j, (i >> j) % 2 == 1, combo
``````
print powerSet([1,2,3])
``````
0 0 0b0 0 False []
0 1 0b0 0 False []
0 2 0b0 0 False []
1 0 0b1 1 True [1]
1 1 0b1 0 False [1]
1 2 0b1 0 False [1]
2 0 0b10 2 False []
2 1 0b10 1 True [2]
2 2 0b10 0 False [2]
3 0 0b11 3 True [1]
3 1 0b11 1 True [1, 2]
3 2 0b11 0 False [1, 2]
4 0 0b100 4 False []
4 1 0b100 2 False []
4 2 0b100 1 True [3]
5 0 0b101 5 True [1]
5 1 0b101 2 False [1]
5 2 0b101 1 True [1, 3]
6 0 0b110 6 False []
6 1 0b110 3 True [2]
6 2 0b110 1 True [2, 3]
7 0 0b111 7 True [1]
7 1 0b111 3 True [1, 2]
7 2 0b111 1 True [1, 2, 3]
None