Python Slip and Slide


#1
  1. Define a function called flip_bit that takes the inputs (number, n).
  2. Flip the nth bit (with the ones bit being the first bit) and store it in result.
  3. Return the result of calling bin(result).

So this is my code.
def flip_bit(number,n):
>>>> mask = (0b1<<n-1)
>>>> number = int(number,2)
>>>> result = mask^number
>>>> print bin(result)

flip_bit('0b10100101', 4)

It works fine on my compiler but for some reason I get an error. Could anyone tell me what is wrong?

Oops, try again. Does your flip_bit function take exactly two arguments (a binary number and the bit to flip)? Your code threw a "int() can't convert non-string with explicit base" error.


#2

https://docs.python.org/2/library/functions.html#int

If x is not a number or if base is given, then x must be a string

I think the problem is that the number parameter should be an integer already.


#3
def flip_bit(number,n):
    mask = (0b1<<n-1)
    #################################
        number = int(number,2) ## You are getting something wacky here.
You don't need to have this.We dont want an int() and we also don't want 
to flip the 2nd bit every time. it's the nth bit we want. the 2 here would 
override the 4 you called.
    ################################
    result = mask^number
    print bin(result) #Here the exercise wanted a return not print

flip_bit('0b10100101', 4) #You can call print to print to console :)

Try this code:

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

print flip_bit(0b10100101, 4)

Good luck mate!