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

Method __add__

algorithms/math/polynomial.py:388–433  ·  view source on GitHub ↗

Add a polynomial, monomial, or scalar to this polynomial. Args: other: Value to add. Returns: The resulting Polynomial. Raises: ValueError: If other is not a valid type.

(self, other: int | float | Fraction | Monomial)

Source from the content-addressed store, hash-verified

386 return num
387
388 def __add__(self, other: int | float | Fraction | Monomial) -> Polynomial:
389 """Add a polynomial, monomial, or scalar to this polynomial.
390
391 Args:
392 other: Value to add.
393
394 Returns:
395 The resulting Polynomial.
396
397 Raises:
398 ValueError: If other is not a valid type.
399 """
400 if isinstance(other, (int, float, Fraction)):
401 return self.__add__(
402 Monomial({}, Polynomial._rationalize_if_possible(other))
403 )
404 elif isinstance(other, Monomial):
405 monos = {m.clone() for m in self.monomials}
406
407 for _own_monos in monos:
408 if _own_monos.equal_upto_scalar(other):
409 scalar = _own_monos.coeff
410 monos -= {_own_monos}
411 temp_variables = {i: other.variables[i] for i in other.variables}
412 monos |= {
413 Monomial(
414 temp_variables,
415 Polynomial._rationalize_if_possible(scalar + other.coeff),
416 )
417 }
418 return Polynomial([z for z in monos])
419
420 monos |= {other.clone()}
421 return Polynomial([z for z in monos])
422 elif isinstance(other, Polynomial):
423 temp = list(z for z in {m.clone() for m in self.all_monomials()})
424
425 p = Polynomial(temp)
426 for o in other.all_monomials():
427 p = p.__add__(o.clone())
428 return p
429 else:
430 raise ValueError(
431 "Can only add int, float, Fraction, Monomials, "
432 "or Polynomials to Polynomials."
433 )
434
435 def __sub__(self, other: int | float | Fraction | Monomial) -> Polynomial:
436 """Subtract a polynomial, monomial, or scalar from this polynomial.

Callers 2

__mul__Method · 0.95
_cycle_index_sym_helperFunction · 0.95

Calls 6

all_monomialsMethod · 0.95
MonomialClass · 0.85
PolynomialClass · 0.85
equal_upto_scalarMethod · 0.80
cloneMethod · 0.45

Tested by

no test coverage detected