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.

5
  • 1
    Python is not C, What problem are you trying to solve using this approach? Commented Feb 13, 2014 at 10:28
  • 1
    "correct but it is not readable" What does that mean O_ó ? The code is hard to understand? Commented Feb 13, 2014 at 10:31
  • @FredrikPihl I am using geng (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. Commented Feb 13, 2014 at 10:31
  • This link could help: stackoverflow.com/questions/13492826/ones-complement-python Commented Feb 13, 2014 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. Commented Feb 13, 2014 at 10:36

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Your idea is super clean!
1

Replace in three steps:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.