1

I have a list of boolean strings. Each string is of length 6. I need to get the complement of each string. E.g, if the string is "111111", then "000000" is expected. My idea is

bin(~int(s,2))[-6:]
  1. convert it to integer and negate it by treating it as a binary number
  2. convert it back to a binary string and use the last 6 characters.

I think it is correct but it is not readable. And it only works for strings of length less than 30. Is there a better and general way to complement a boolean string?

I googled a 3rd party package "bitstring". However, it is too much for my code.

Peng Zhang
  • 3,475
  • 4
  • 33
  • 41
  • 1
    Python is not C, What problem are you trying to solve using this approach? – Fredrik Pihl Feb 13 '14 at 10:28
  • 1
    "correct but it is not readable" What does that mean O_ó ? The code is hard to understand? – luk32 Feb 13 '14 at 10:31
  • @FredrikPihl I am using geng (http://pallini.di.uniroma1.it/), a subroutine of nauty to generate graphs. The format of the output is a string of characters and each character encodes 6 binary bits. – Peng Zhang Feb 13 '14 at 10:31
  • This link could help: http://stackoverflow.com/questions/13492826/ones-complement-python – David Dahan Feb 13 '14 at 10:32
  • @luk32 Without the explanation of context, I find it confusing myself. Anyway, I should just treat this "complementing" as "replacing" as the two answers suggest. – Peng Zhang Feb 13 '14 at 10:36

2 Answers2

6

Well, you basically have a string in which you want to change all the 1s to 0s and vice versa. I think I would forget about the Boolean meaning of the strings and just use maketrans to make a translation table:

from string import maketrans

complement_tt = maketrans('01', '10')

s = '001001'
s = s.translate(complement_tt)  # It's now '110110'
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

Replace in three steps:

>>> s = "111111"
>>> s.replace("1", "x").replace("0", "1").replace("x", "0")
'000000'