排他的論理和

Python Published at April 8, 2025, 1:49 p.m. by admin@senrigan.org

2つの入力のうち一方が真でもう一方が偽となるもの

def xor(a, b):
    return [x ^ y for x, y in zip(a, b)]

a = [1,0,0,1,1]
b = [0,1,1,0,0]
print(xor(a, b)) # => [1,1,1,1,1]

堅牢バージョン

def xor(a, b):
    if not isinstance(a, list) or not isinstance(b, list):
        raise TypeError("Both arguments must be lists.")
    if len(a) != len(b):
        raise ValueError("Lists must have the same length.")
    try:
        return [int(x) ^ int(y) for x, y in zip(a, b)]
    except TypeError:
        raise TypeError("List elements must be integers or booleans.")
print(xor(a,b)) # => [1,1,1,1,1]