A polynomial represented as a set of Monomial terms.
| 342 | |
| 343 | |
| 344 | class Polynomial: |
| 345 | """A polynomial represented as a set of Monomial terms.""" |
| 346 | |
| 347 | def __init__( |
| 348 | self, monomials: Iterable[int | float | Fraction | Monomial] |
| 349 | ) -> None: |
| 350 | """Create a polynomial from an iterable of monomials or scalars. |
| 351 | |
| 352 | Args: |
| 353 | monomials: An iterable of Monomial, int, float, or Fraction values. |
| 354 | |
| 355 | Raises: |
| 356 | ValueError: If an element is not a valid type. |
| 357 | """ |
| 358 | self.monomials: set = set() |
| 359 | for m in monomials: |
| 360 | if any(map(lambda x: isinstance(m, x), [int, float, Fraction])): |
| 361 | self.monomials |= {Monomial({}, m)} |
| 362 | elif isinstance(m, Monomial): |
| 363 | self.monomials |= {m} |
| 364 | else: |
| 365 | raise ValueError( |
| 366 | "Iterable should have monomials, int, float, or Fraction." |
| 367 | ) |
| 368 | self.monomials -= {Monomial({}, 0)} |
| 369 | |
| 370 | @staticmethod |
| 371 | def _rationalize_if_possible( |
| 372 | num: int | float | Fraction, |
| 373 | ) -> Fraction | float: |
| 374 | """Convert numbers to Fraction when possible. |
| 375 | |
| 376 | Args: |
| 377 | num: A numeric value. |
| 378 | |
| 379 | Returns: |
| 380 | A Fraction if the input is Rational, otherwise the original value. |
| 381 | """ |
| 382 | if isinstance(num, Rational): |
| 383 | res = Fraction(num, 1) |
| 384 | return Fraction(res.numerator, res.denominator) |
| 385 | else: |
| 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__( |
no outgoing calls