[Python] Extending sympy variable definition to binary

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to extend the symbol class to a binary variable, where + would mimic an XOR operator such that

    x + y -> x + y

    x + x -> 0

    I have referenced the this code here and added _eval_add but it doesn't seem to call the function.

    This is my code:

    from sympy import Symbol, Integer

    class XorBinary(Symbol):

    def _eval_power(self, other):
    if other % 2 == 0:
    return Integer(1)
    elif self == other:
    return Integer(0)
    else:
    return self

    def _eval_add(self, other):
    print("add", self, other)
    if self == other:
    return Integer(0)
    return self

    # Example usage
    x = XorBinary("x")
    y = XorBinary("y")

    print("x^2 =", x**2) # -> 1
    print("x^3 =", x**3) # -> x
    print("x^0 =", x**0) # -> 1
    print("x*x =", x*x) # -> x
    print("x+x =", x + x) # -> x
    print("x+y =", x+y) # normal sum (unless XOR enforced)

    Continue reading...

Compartilhe esta Página