MCPcopy
hub / github.com/keon/algorithms / __add__

Method __add__

algorithms/math/polynomial.py:90–117  ·  view source on GitHub ↗

Add two monomials or a monomial with a scalar. Args: other: A Monomial, int, float, or Fraction to add. Returns: The resulting Monomial. Raises: ValueError: If monomials have different variables.

(self, other: int | float | Fraction)

Source from the content-addressed store, hash-verified

88 return other.variables == self.variables
89
90 def __add__(self, other: int | float | Fraction) -> Monomial:
91 """Add two monomials or a monomial with a scalar.
92
93 Args:
94 other: A Monomial, int, float, or Fraction to add.
95
96 Returns:
97 The resulting Monomial.
98
99 Raises:
100 ValueError: If monomials have different variables.
101 """
102 if isinstance(other, (int, float, Fraction)):
103 return self.__add__(Monomial({}, Monomial._rationalize_if_possible(other)))
104
105 if not isinstance(other, Monomial):
106 raise ValueError("Can only add monomials, ints, floats, or Fractions.")
107
108 if self.variables == other.variables:
109 mono = {i: self.variables[i] for i in self.variables}
110 return Monomial(
111 mono, Monomial._rationalize_if_possible(self.coeff + other.coeff)
112 ).clean()
113
114 raise ValueError(
115 f"Cannot add {str(other)} to {self.__str__()} "
116 "because they don't have same variables."
117 )
118
119 def __eq__(self, other: object) -> bool:
120 """Check equality of two monomials.

Callers 1

__sub__Method · 0.95

Calls 4

__str__Method · 0.95
MonomialClass · 0.85
cleanMethod · 0.80

Tested by

no test coverage detected