14. Slip and Slide


#1



https://www.codecademy.com/courses/python-intermediate-en-KE1UJ/2/4?curriculum_id=4f89dab3d788890003000096#


Oops, try again. Your function fails on flip_bit('0b111', 2). It returns "0b110" when it should return "0b101".


def flip_bit(number, n):
    mask = n << (n -1)
    result = n ^ mask
    return bin(result)


#2

We're shifting mask value not n
mask = n << (n -1) is creating problem.
As elementary maskbit will be 0b1.

I know Bitwise operators are rusty/not clear at first go!
I hope it helps! :slight_smile:

I strongly suggest you to read this thread!! :slight_smile:


#3

So sorry, but I still don't get it. You're good at explaining, but I just don't get Python.

def flip_bit(number, n):
    mask = 0b1 << n
    result = n ^ mask
    return bin(result)

#4

number - the digit whose nth bit will be masked
n - Number of shifts
We take an elementary maskbit that can be 0b1 (right?)
We shift it using << till n times.
our maskbit is ready!

Then we use this maskbit variable with ^ operator.
what ^ does?

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

Now we operate our maskbit ,^ and the number together!
then simply xor (^) input with maskbit? #updated
Am I clear ? :slight_smile:
If not ,then do tell!


#5

I feel so bad, but I still don't get it.:sweat:

def flip_bit(number, n):
    mask = 0b1 << n
    result = mask ^ number
    return bin(result)

#6

No worry! here...
pic updated--

I apologize for updating pics so many times!

I was actually trying to make an example for ya!
Do reply it is clear or not! :slight_smile:

at 11th digit, input had 0 and our maskbit had 1 which xor-ed (^) to 1 ? right!

update**
Points --
You can see when we shifted 0b1 to 10th ,it actually shifted to 11th position?
That's why we subtracted 1 from n so it shifts exactly at n not n + 1.


#7

Sorry for the delay in replying, but thanks so much once again!:grin:

def flip_bit(number,n):
    mask = 0b1 << (n-1)
    result = number ^ mask
    return bin(result)

#8

Cheers!!! :slight_smile:
keep your spirits up :thumbsup:


#9

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