def different(s):
x = len(s)
for i in range(1, 1 << x):
u.append([s[j] for j in range(x) if (i & (1 << j))])
It takes a list and makes different combinations
(a,b,c) = ((a,b,c),(a,b),(a,c) ...)
But what does the range do? From 1 to what. I don’t understand the "<<"
and also, if (i & (1 << j)) what does this do? It checks if i and 2 to the power of j? Doesn’t make any sense to me.
The range function returns a list of numbers from zero to the given number minus one. It also has two- and three-argument forms (see the doc for more info):
<<is the left-shift operator, and has the effect of multiplying the left hand side by two to the power of the right hand side:Thus the above range function (
range(1, 1 << x)) returns[1, 2, 3, ..., 2**x - 1].In the seconds usage of
<<, the left-shift is being used as a bit-mask. It moves the 1-bit into the j-th bit, and performs a bit-wise and with i, so the result will be non-zero (and pass theiftest) if and only if the j-th bit of i is set. For example:In short,
x & (1 << y)is non-zero iff the y-th bit of x is set.