xteetsx
xteetsx

Reputation: 53

make binary number its 'opposite' in python

trying to take a list of binary numbers, and display their 'opposites', im putting this word in quotes because I'm not sure if it's the best way to describe what I mean.

board=[1,10,101]

I want to make a function that will show the complement of opposite of these numbers like this:

newboard=[0,01,010]

basically swapping the 0 for a 1 and the 1 for a 0. Since they are integers I cant iterate through each binary number and manually change the value, I've tried using two's compliment but that doesn't semantically do what I'm trying to do it seems. Does anyone know a function for how to do this, or what this process would be called? thanks!

Upvotes: 1

Views: 2041

Answers (4)

Wso
Wso

Reputation: 302

You can swap all the ones for zeros and all the zeros for ones inside every string. To do this simple iterate over the list, and for each value, create a new entry swapping 1 and 0. In order to preform the swap, replace '1' with a value thats never used (such as 'U'), assign '0' to '1' and assign the temp value 'U' to '0'.

newboard = [a.replace('1','U').replace('0','1').replace('U','0') for a in board]

Upvotes: 0

panzerpower
panzerpower

Reputation: 63

I believe what you are referring to is just called complementing numbers; you are trying to flipping the digits of binary numbers. The natural thing to do is to use the XOR operator. Consider the following piece of code:

get_bin = lambda x: format(x, 'b')
def Complement_binary(x):
    complemented = []
    for num in x:
        i = 1
        while i <= num:
            i = i << 1
        complemented.append(get_bin((i - 1) ^ num))
    return complemented

The Complement_binary function receives a list of numbers and returns a list of numbers in binary representation in strings (get_bin converts the numbers to binary numbers in strings). If you don't want strings, you may remove the get_bin function in complemented.append(get_bin((i - 1) ^ num)).

Source for get_bin function: https://stackoverflow.com/a/21732313/6833761 by @Martin Thoma

Upvotes: 0

davidejones
davidejones

Reputation: 1949

You can't really store [0, 01, 010] in a list as it just becomes [0, 1, 10] you can use strings though

def reverse_binary(input):
    reversed = []
    for x in [list(str(x)) for x in input]:
        reversed.append(''.join(['%s' % (int(x) ^ 1) for x in x]))
    return reversed


if __name__ == '__main__':
    print(reverse_binary([1, 10, 101]))

Upvotes: 0

fjarino
fjarino

Reputation: 191

Can you represent your binary numbers as strings? Then you could simply do the following:

opposite = { '0':'1', '1':'0'}
board=['1', '10', '101']
newboard = [''.join([opposite[c] for c in n]) for n in board]

Upvotes: 1

Related Questions