-5

I got a code like this:

def f(x):
    return 1 if x & (x-1)  == 0 else 0
print(f(20))

Can anyone explain what this function is doing?

i need to understand x & x-1 meaning.

  • 1
    Search for ["python operators"](https://docs.python.org/3.4/library/operator.html). It is a 'bit-wise and' here, given x is an integer (20): however, it _could_ do something else for a custom type. See the page above, and use the terms there to search out. – user2864740 May 12 '20 at 04:56
  • 3
    [Bitwise operators](https://wiki.python.org/moin/BitwiseOperators) to be specific – rdas May 12 '20 at 04:56
  • 2
    While I appreciate you guys closing and linking to the question where I have the highest voted and accepted answer, I think this is not strictly a dupe of that. The `x & (x-1)` pattern does *use* bitwise operators but it's more to do with the fact the only way to get a zero out of it is if `x` is a power of two. That's slightly different to just asking what `&` does. – paxdiablo May 12 '20 at 05:04

1 Answers1

1

First up, go and have a look at this answer to see how bitwise operators work. Once, you understand that, just be aware that the expression x & x-1 (with unsigned x, at least) will give you zero if and only if x is a power of two or zero (I consider zero to be a special case simply because zero and'ed with anything gives you zero).

The reason x & (x - 1) gives you zero for a power of two is because a power of two takes the binary form on the first line below (a single 1 bit followed by zero or more 0 bits) and subtracting one from it gives you the second form (with the bits all inverted from that single 1 bit onward):

10000000 = 128 (128)
01111111 = 127 (64 + 32 + 16 + 8 + 4 + 2 + 1)
--------   AND
00000000

So, if you and them, all bits become zero. Note that no non-power-of-two other than zero has this property, for example 42:

00101010 = 42 (32 + 8 + 2)
00101001 = 41 (32 + 8 + 1)
--------  AND
00101000 = 40 (32 + 8)
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953