Y dis no work? 14. Slip and Slide



cries in binary

def flip_bit(number, n):
    result = number << n
    return bin(result)



    result = number << n

The << operation alone will not return the nth bit.

Instead, why not try something like:

    result = number ^ (0b1 >> n - 1)


You seem to have the wrong operation here. Left-Shifting the number just multiplies it:

>>> number = 5 # for example
>>> bin(number)
>>> bin(number << 2)

in other words, you just take the pattern and move it to the left by a number of places. Therefore, using a mask like this:

>>>mask = 1 << 3

so you have just one bit set true, in the (fourth) place. It's the fourth place because doing nothing (ie shifting by zero) leaves the first bit set 0b00001, shifting by one moves it into the second place, and so on [see footnote].

Once you have the mask set up, you use the xor (^) operator to flip that bit in the original number.

def flip(bit, number):
    mask=1 << (bit-1) # should check that bit >= 0 !
    return number ^ mask

By the way,

has the shift operator pointing the wrong way!

[footnote]: in the real world, the rightmost bit usually labelled zero, so all the bits run from 0—15 or 0—63 etc, so you don't have to do the subtraction.

Hope that helps

Tim F


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.