def__new__( cls, left: Iterable[SurrealNumber] = (), right: Iterable[SurrealNumber] = (), name: str = "", ) -> SurrealNumber: """Create a new surreal number or return an existing one.""" key = (frozenset(left), frozenset(right)) ifnotall(isinstance(x, SurrealNumber) for x in key[0]): raise TypeError("Left set must contain only surreal numbers.") ifnotall(isinstance(x, SurrealNumber) for x in key[1]): raise TypeError("Right set must contain only surreal numbers.") if key notin cls.No: instance = super().__new__(cls) instance.L, instance.R = key cls.No[key] = instance if name != "": cls.No[key].set_alias(name) return cls.No[key]
defset_alias(self, name: str) -> None: """Set an alias for the surreal number.""" ifselfinself.aliases: raise ValueError(f"Alias already exists for {self}") self.aliases[self] = name
@lru_cache(maxsize=1 << 24) def__ge__(self, other: SurrealNumber) -> bool: """Check if this surreal number is greater than or equal to another.""" returnnotany(right <= other for right inself.R) andnotany(left >= selffor left in other.L)
@lru_cache(maxsize=1 << 24) def__le__(self, other: SurrealNumber) -> bool: """Check if this surreal number is less than or equal to another.""" return other >= self
@lru_cache(maxsize=1 << 24) def__add__(self, other: SurrealNumber) -> SurrealNumber: """Add two surreal numbers.""" return SurrealNumber( {xL + other for xL inself.L} | {self + yL for yL in other.L}, {xR + other for xR inself.R} | {self + yR for yR in other.R}, )
@lru_cache(maxsize=1 << 24) def__neg__(self) -> SurrealNumber: """Negate the surreal number.""" return SurrealNumber({-x for x inself.R}, {-x for x inself.L})
@lru_cache(maxsize=1 << 24) def__mul__(self, other: SurrealNumber) -> SurrealNumber: """Multiply two surreal numbers.""" L1 = {xL * other + self * yL - xL * yL for xL inself.L for yL in other.L} L2 = {xR * other + self * yR - xR * yR for xR inself.R for yR in other.R} R1 = {xL * other + self * yR - xL * yR for xL inself.L for yR in other.R} R2 = {xR * other + self * yL - xR * yL for xR inself.R for yL in other.L} return SurrealNumber(L1 | L2, R1 | R2)
@lru_cache(maxsize=1 << 24) defto_string(self, alias: bool = True) -> str: """Return a string representation of the surreal number.""" if alias andselfinself.aliases: returnself.aliases[self] left_str = ", ".join(sorted(x.to_string(alias) for x inself.L)) right_str = ", ".join(sorted(x.to_string(alias) for x inself.R)) returnf"{{{left_str} | {right_str}}}"
def__repr__(self) -> str: """Return a string representation of the surreal number.""" returnself.to_string()
def__str__(self) -> str: """Return a string representation of the surreal number.""" returnself.to_string()