We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value).
Sometimes it is required to inverse the bits i.e., 0’s to 1’s ( zeros to ones) and 1’s to 0’s (ones to zeros). Here are there few ways by which we can inverse the bits in Python.
1) Using Loops: By iterating each and every bit we can change the bit 1 to bit 0 and vice-versa.
Python3
bit_s = '1010' inverse_s = '' for i in bit_s: if i = = '0' : inverse_s + = '1' else : inverse_s + = '0' print ( "Inversed string is " , inverse_s) |
Output:
Inversed string is 0101
Time complexity: O(n), where n is the length of the input string bit_s.
Auxiliary space: O(n), where n is the length of the input string bit_s.
2) Using Dictionary: Dictionaries are very fast in accessing an element, which it takes O(1) time complexity.
Python3
# create a dictionary b_dict = { '0' : '1' , '1' : '0' } bit_s = '1010' inverse_s = '' for i in bit_s: inverse_s + = b_dict[i] print ( "Inversed string is" , inverse_s) |
Output:
Inversed string is 0101
3) Using List comprehension: List comprehensions are the short hand notations of accessing, adding, manipulating a list.
Python3
bit_s = '1010' # using ternary operator with # list comprehension inverse_s = ' '.join([' 1 ' if i == ' 0 ' else ' 0 ' for i in bit_s]) print ( "Inversed string is" , inverse_s) |
Output:
Inversed string is 0101
4) Using replace() method of strings: In python, strings has a built-in method i.e., string.replace(existing_characters, new_characters), which replaces all the existing_characters with new_characters.
Python3
bit_s = '1010' # replace "1" with "2" # output : "2020" inverse_s = bit_s.replace( '1' , '2' ) # replace "0" with "1" # output : "2121" inverse_s = inverse_s.replace( '0' , '1' ) # replace "0" with "1" # output : "0101" inverse_s = inverse_s.replace( '2' , '0' ) print ( "Inversed string is" , inverse_s) |
Output:
Inversed string is 0101
5) Using bit-wise XOR operator: XOR operator Returns 1 if one of the bit is 1 and other is 0 else returns false.
Python3
bit_s = '1010' # convert binary string # into integer temp = int (bit_s, 2 ) # applying Ex-or operator # b/w 10 and 31 inverse_s = temp ^ ( 2 * * ( len (bit_s) + 1 ) - 1 ) # convert the integer result # into binary result and then # slicing of the '0b1' # binary indicator rslt = bin (inverse_s)[ 3 : ] # print the result print ( "Inversed string is" , rslt ) |
Output:
Inversed string is 0101