-3

I have two binary strings (not integer) for example 0101 and 0010, I need to XOR these two binary strings and then XOR the each bit of the result again. XOR of these two results in 0111, now I want to achieve the result 0 xor 1 xor 1 xor 1. How can I achieve it in python?

I have XORed the two strings in result variable, now I need to find the XOR of each bit in result

a = "0101"
b = "0010"
result = []
for x, y in zip(a, b):
    if x == y:
        result.append('0')
    else:
        result.append('1')
final = []
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
efe373
  • 151
  • 2
  • 11
  • What have you tried so far? – Klaus D. Jan 18 '23 at 08:55
  • `reduce` , define a function... – Gameplay Jan 18 '23 at 08:55
  • 1
    How are your "binary strings" represented ? –  Jan 18 '23 at 08:57
  • Please don't post solutions into questions. Also as I mentioned below you mixed the two approaches. If you create `result` as an int, why transform it to a string? You can easily do a parity check on an int – Tomerikoo Jan 18 '23 at 09:24
  • @Tomerikoo Actually my solution was wrong for my case. I shouldn't use integers because my strings can be up to 2K bits long. That was why I was avoiding integers. Thanks anyway – efe373 Jan 18 '23 at 13:28
  • Do you actually need that XOR of the two strings, or only the final XOR result (i.e., one bit)? – Kelly Bundy Feb 04 '23 at 13:19

1 Answers1

1

Working with strings

You can use the same logic you used on two inputs, to reduce a single input:

from functools import reduce

final = reduce(lambda x, y: '0' if x == y else '1', result)

Working with ints

Alternatively, you can just transform the inputs to ints by using int(x, 2). So you can have:

result = int(a, 2) ^ int(b, 2)

And now you just need to bit-wise XOR result. That is mentioned here and is basically a parity check which can be easily done (Python >= 3.10) with

final = result.bit_count() & 1
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61