-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathpolynomial.py
More file actions
708 lines (574 loc) · 23 KB
/
polynomial.py
File metadata and controls
708 lines (574 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
"""
Polynomial and Monomial Arithmetic
A symbolic algebra system for polynomials and monomials supporting addition,
subtraction, multiplication, division, substitution, and polynomial long
division with Fraction-based exact arithmetic.
Reference: https://en.wikipedia.org/wiki/Polynomial
Complexity:
Time: Varies by operation
Space: O(number of monomials)
"""
from __future__ import annotations
from collections.abc import Iterable
from fractions import Fraction
from functools import reduce
from numbers import Rational
class Monomial:
"""A monomial represented by a coefficient and variable-to-power mapping."""
def __init__(
self, variables: dict[int, int], coeff: int | float | Fraction | None = None
) -> None:
"""Create a monomial with the given variables and coefficient.
Args:
variables: Dictionary mapping variable indices to their powers.
coeff: The coefficient (defaults to 0 if empty, 1 otherwise).
Examples:
>>> Monomial({1: 1}) # (a_1)^1
>>> Monomial({1: 3, 2: 2}, 12) # 12(a_1)^3(a_2)^2
"""
self.variables = dict()
if coeff is None:
coeff = Fraction(0, 1) if len(variables) == 0 else Fraction(1, 1)
elif coeff == 0:
self.coeff = Fraction(0, 1)
return
if len(variables) == 0:
self.coeff = Monomial._rationalize_if_possible(coeff)
return
for i in variables:
if variables[i] != 0:
self.variables[i] = variables[i]
self.coeff = Monomial._rationalize_if_possible(coeff)
@staticmethod
def _rationalize_if_possible(
num: int | float | Fraction,
) -> Fraction | float:
"""Convert numbers to Fraction when possible.
Args:
num: A numeric value.
Returns:
A Fraction if the input is Rational, otherwise the original value.
"""
if isinstance(num, Rational):
res = Fraction(num, 1)
return Fraction(res.numerator, res.denominator)
else:
return num
def equal_upto_scalar(self, other: object) -> bool:
"""Check if other is a monomial equivalent to self up to scalar multiple.
Args:
other: Another Monomial to compare.
Returns:
True if both have the same variables with the same powers.
Raises:
ValueError: If other is not a Monomial.
"""
if not isinstance(other, Monomial):
raise ValueError("Can only compare monomials.")
return other.variables == self.variables
def __add__(self, other: int | float | Fraction) -> Monomial:
"""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.
"""
if isinstance(other, (int, float, Fraction)):
return self.__add__(Monomial({}, Monomial._rationalize_if_possible(other)))
if not isinstance(other, Monomial):
raise ValueError("Can only add monomials, ints, floats, or Fractions.")
if self.variables == other.variables:
mono = {i: self.variables[i] for i in self.variables}
return Monomial(
mono, Monomial._rationalize_if_possible(self.coeff + other.coeff)
).clean()
raise ValueError(
f"Cannot add {str(other)} to {self.__str__()} "
"because they don't have same variables."
)
def __eq__(self, other: object) -> bool:
"""Check equality of two monomials.
Args:
other: Another Monomial to compare.
Returns:
True if both monomials are equal.
"""
if not isinstance(other, Monomial):
return NotImplemented
return self.equal_upto_scalar(other) and self.coeff == other.coeff
def __mul__(self, other: int | float | Fraction) -> Monomial:
"""Multiply two monomials or a monomial with a scalar.
Args:
other: A Monomial, int, float, or Fraction to multiply.
Returns:
The resulting Monomial.
Raises:
ValueError: If other is not a valid type.
"""
if isinstance(other, (float, int, Fraction)):
mono = {i: self.variables[i] for i in self.variables}
return Monomial(
mono, Monomial._rationalize_if_possible(self.coeff * other)
).clean()
if not isinstance(other, Monomial):
raise ValueError("Can only multiply monomials, ints, floats, or Fractions.")
else:
mono = {i: self.variables[i] for i in self.variables}
for i in other.variables:
if i in mono:
mono[i] += other.variables[i]
else:
mono[i] = other.variables[i]
temp = dict()
for k in mono:
if mono[k] != 0:
temp[k] = mono[k]
return Monomial(
temp, Monomial._rationalize_if_possible(self.coeff * other.coeff)
).clean()
def inverse(self) -> Monomial:
"""Compute the multiplicative inverse of this monomial.
Returns:
The inverse Monomial.
Raises:
ValueError: If the coefficient is zero.
"""
mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}
for i in mono:
mono[i] *= -1
if self.coeff == 0:
raise ValueError("Coefficient must not be 0.")
return Monomial(mono, Monomial._rationalize_if_possible(1 / self.coeff)).clean()
def __truediv__(self, other: int | float | Fraction) -> Monomial:
"""Divide this monomial by another monomial or scalar.
Args:
other: A Monomial, int, float, or Fraction divisor.
Returns:
The resulting Monomial.
Raises:
ValueError: If dividing by zero.
"""
if isinstance(other, (int, float, Fraction)):
mono = {i: self.variables[i] for i in self.variables}
if other == 0:
raise ValueError("Cannot divide by 0.")
return Monomial(
mono, Monomial._rationalize_if_possible(self.coeff / other)
).clean()
o = other.inverse()
return self.__mul__(o)
def __floordiv__(self, other: int | float | Fraction) -> Monomial:
"""Floor division (same as true division for monomials).
Args:
other: A Monomial, int, float, or Fraction divisor.
Returns:
The resulting Monomial.
"""
return self.__truediv__(other)
def clone(self) -> Monomial:
"""Create a deep copy of this monomial.
Returns:
A new Monomial with the same variables and coefficient.
"""
temp_variables = {i: self.variables[i] for i in self.variables}
return Monomial(
temp_variables, Monomial._rationalize_if_possible(self.coeff)
).clean()
def clean(self) -> Monomial:
"""Remove variables with zero power.
Returns:
A cleaned Monomial.
"""
temp_variables = {
i: self.variables[i] for i in self.variables if self.variables[i] != 0
}
return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff))
def __sub__(self, other: int | float | Fraction) -> Monomial:
"""Subtract a value from this monomial.
Args:
other: A Monomial, int, float, or Fraction to subtract.
Returns:
The resulting Monomial.
Raises:
ValueError: If monomials have different variables.
"""
if isinstance(other, (int, float, Fraction)):
mono = {
i: self.variables[i] for i in self.variables if self.variables[i] != 0
}
if len(mono) != 0:
raise ValueError("Can only subtract like monomials.")
other_term = Monomial(mono, Monomial._rationalize_if_possible(other))
return self.__sub__(other_term)
if not isinstance(other, Monomial):
raise ValueError("Can only subtract monomials")
return self.__add__(other.__mul__(Fraction(-1, 1)))
def __hash__(self) -> int:
"""Hash based on the underlying variables.
Returns:
An integer hash value.
"""
arr = []
for i in sorted(self.variables):
if self.variables[i] > 0:
for _ in range(self.variables[i]):
arr.append(i)
return hash(tuple(arr))
def all_variables(self) -> set:
"""Get the set of all variable indices in this monomial.
Returns:
A set of variable indices.
"""
return set(sorted(self.variables.keys()))
def substitute(
self,
substitutions: int | float | Fraction | dict[int, int | float | Fraction],
) -> Fraction:
"""Evaluate the monomial by substituting values for variables.
Args:
substitutions: A single value applied to all variables, or a
dict mapping variable indices to values.
Returns:
The evaluated result.
Raises:
ValueError: If some variables are not given values.
"""
if isinstance(substitutions, (int, float, Fraction)):
substitutions = {
v: Monomial._rationalize_if_possible(substitutions)
for v in self.all_variables()
}
else:
if not self.all_variables().issubset(set(substitutions.keys())):
raise ValueError("Some variables didn't receive their values.")
if self.coeff == 0:
return Fraction(0, 1)
ans = Monomial._rationalize_if_possible(self.coeff)
for k in self.variables:
ans *= Monomial._rationalize_if_possible(
substitutions[k] ** self.variables[k]
)
return Monomial._rationalize_if_possible(ans)
def __str__(self) -> str:
"""Get a string representation of the monomial.
Returns:
A human-readable string.
"""
if len(self.variables) == 0:
return str(self.coeff)
result = str(self.coeff)
result += "("
for i in self.variables:
temp = f"a_{str(i)}"
if self.variables[i] > 1:
temp = "(" + temp + f")**{self.variables[i]}"
elif self.variables[i] < 0:
temp = "(" + temp + f")**(-{-self.variables[i]})"
elif self.variables[i] == 0:
continue
else:
temp = "(" + temp + ")"
result += temp
return result + ")"
class Polynomial:
"""A polynomial represented as a set of Monomial terms."""
def __init__(
self, monomials: Iterable[int | float | Fraction | Monomial]
) -> None:
"""Create a polynomial from an iterable of monomials or scalars.
Args:
monomials: An iterable of Monomial, int, float, or Fraction values.
Raises:
ValueError: If an element is not a valid type.
"""
self.monomials: set = set()
for m in monomials:
if any(map(lambda x: isinstance(m, x), [int, float, Fraction])):
self.monomials |= {Monomial({}, m)}
elif isinstance(m, Monomial):
self.monomials |= {m}
else:
raise ValueError(
"Iterable should have monomials, int, float, or Fraction."
)
self.monomials -= {Monomial({}, 0)}
@staticmethod
def _rationalize_if_possible(
num: int | float | Fraction,
) -> Fraction | float:
"""Convert numbers to Fraction when possible.
Args:
num: A numeric value.
Returns:
A Fraction if the input is Rational, otherwise the original value.
"""
if isinstance(num, Rational):
res = Fraction(num, 1)
return Fraction(res.numerator, res.denominator)
else:
return num
def __add__(self, other: int | float | Fraction | Monomial) -> Polynomial:
"""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.
"""
if isinstance(other, (int, float, Fraction)):
return self.__add__(
Monomial({}, Polynomial._rationalize_if_possible(other))
)
elif isinstance(other, Monomial):
monos = {m.clone() for m in self.monomials}
for _own_monos in monos:
if _own_monos.equal_upto_scalar(other):
scalar = _own_monos.coeff
monos -= {_own_monos}
temp_variables = {i: other.variables[i] for i in other.variables}
monos |= {
Monomial(
temp_variables,
Polynomial._rationalize_if_possible(scalar + other.coeff),
)
}
return Polynomial([z for z in monos])
monos |= {other.clone()}
return Polynomial([z for z in monos])
elif isinstance(other, Polynomial):
temp = list(z for z in {m.clone() for m in self.all_monomials()})
p = Polynomial(temp)
for o in other.all_monomials():
p = p.__add__(o.clone())
return p
else:
raise ValueError(
"Can only add int, float, Fraction, Monomials, "
"or Polynomials to Polynomials."
)
def __sub__(self, other: int | float | Fraction | Monomial) -> Polynomial:
"""Subtract a polynomial, monomial, or scalar from this polynomial.
Args:
other: Value to subtract.
Returns:
The resulting Polynomial.
Raises:
ValueError: If other is not a valid type.
"""
if isinstance(other, (int, float, Fraction)):
return self.__sub__(
Monomial({}, Polynomial._rationalize_if_possible(other))
)
elif isinstance(other, Monomial):
monos = {m.clone() for m in self.all_monomials()}
for _own_monos in monos:
if _own_monos.equal_upto_scalar(other):
scalar = _own_monos.coeff
monos -= {_own_monos}
temp_variables = {i: other.variables[i] for i in other.variables}
monos |= {
Monomial(
temp_variables,
Polynomial._rationalize_if_possible(scalar - other.coeff),
)
}
return Polynomial([z for z in monos])
to_insert = other.clone()
to_insert.coeff *= -1
monos |= {to_insert}
return Polynomial([z for z in monos])
elif isinstance(other, Polynomial):
p = Polynomial(list(z for z in {m.clone() for m in self.all_monomials()}))
for o in other.all_monomials():
p = p.__sub__(o.clone())
return p
else:
raise ValueError(
"Can only subtract int, float, Fraction, "
"Monomials, or Polynomials from Polynomials."
)
def __mul__(self, other: int | float | Fraction | Monomial) -> Polynomial:
"""Multiply this polynomial by another polynomial, monomial, or scalar.
Args:
other: Value to multiply by.
Returns:
The resulting Polynomial.
Raises:
ValueError: If other is not a valid type.
"""
if isinstance(other, (int, float, Fraction, Monomial)):
result = Polynomial([])
monos = {m.clone() for m in self.all_monomials()}
for m in monos:
result = result.__add__(m.clone() * other)
return result
elif isinstance(other, Polynomial):
temp_self = {m.clone() for m in self.all_monomials()}
temp_other = {m.clone() for m in other.all_monomials()}
result = Polynomial([])
for i in temp_self:
for j in temp_other:
result = result.__add__(i * j)
return result
else:
raise ValueError(
"Can only multiple int, float, Fraction, "
"Monomials, or Polynomials with Polynomials."
)
def __floordiv__(self, other: int | float | Fraction | Monomial) -> Polynomial:
"""Floor division (same as true division for polynomials).
Args:
other: Divisor value.
Returns:
The resulting Polynomial.
"""
return self.__truediv__(other)
def __truediv__(self, other: int | float | Fraction | Monomial) -> Polynomial:
"""Divide this polynomial by another value.
Args:
other: Divisor (int, float, Fraction, Monomial, or Polynomial).
Returns:
The quotient Polynomial.
Raises:
ValueError: If other is not a valid type.
"""
if isinstance(other, (int, float, Fraction)):
return self.__truediv__(Monomial({}, other))
elif isinstance(other, Monomial):
poly_temp = reduce(
lambda acc, val: acc + val,
map(lambda x: x / other, [z for z in self.all_monomials()]),
Polynomial([Monomial({}, 0)]),
)
return poly_temp
elif isinstance(other, Polynomial):
quotient, remainder = self.poly_long_division(other)
return quotient
raise ValueError(
"Can only divide a polynomial by an int, float, "
"Fraction, Monomial, or Polynomial."
)
def clone(self) -> Polynomial:
"""Create a deep copy of this polynomial.
Returns:
A new Polynomial with cloned monomials.
"""
return Polynomial(list({m.clone() for m in self.all_monomials()}))
def variables(self) -> set:
"""Get all variable indices present in this polynomial.
Returns:
A set of variable indices.
"""
res = set()
for i in self.all_monomials():
res |= {j for j in i.variables}
res = list(res)
return set(res)
def all_monomials(self) -> Iterable[Monomial]:
"""Get all non-zero monomials in this polynomial.
Returns:
A set of Monomial terms.
"""
return {m for m in self.monomials if m != Monomial({}, 0)}
def __eq__(self, other: object) -> bool:
"""Check equality of two polynomials.
Args:
other: Another Polynomial, Monomial, or scalar.
Returns:
True if both represent the same polynomial.
Raises:
ValueError: If other is not a valid type.
"""
if isinstance(other, (int, float, Fraction)):
other_poly = Polynomial([Monomial({}, other)])
return self.__eq__(other_poly)
elif isinstance(other, Monomial):
return self.__eq__(Polynomial([other]))
elif isinstance(other, Polynomial):
return self.all_monomials() == other.all_monomials()
else:
raise ValueError(
"Can only compare a polynomial with an int, "
"float, Fraction, Monomial, or another Polynomial."
)
def subs(
self,
substitutions: int | float | Fraction | dict[int, int | float | Fraction],
) -> int | float | Fraction:
"""Evaluate the polynomial by substituting values for variables.
Args:
substitutions: A single value applied to all variables, or a
dict mapping variable indices to values.
Returns:
The evaluated result.
Raises:
ValueError: If some variables are not given values.
"""
if isinstance(substitutions, (int, float, Fraction)):
substitutions = {
i: Polynomial._rationalize_if_possible(substitutions)
for i in set(self.variables())
}
return self.subs(substitutions)
elif not isinstance(substitutions, dict):
raise ValueError("The substitutions should be a dictionary.")
if not self.variables().issubset(set(substitutions.keys())):
raise ValueError("Some variables didn't receive their values.")
ans = 0
for m in self.all_monomials():
ans += Polynomial._rationalize_if_possible(m.substitute(substitutions))
return Polynomial._rationalize_if_possible(ans)
def __str__(self) -> str:
"""Get a formatted string representation of the polynomial.
Returns:
A human-readable string.
"""
sorted_monos = sorted(
self.all_monomials(),
key=lambda m: sorted(m.variables.items(), reverse=True),
reverse=True,
)
return " + ".join(str(m) for m in sorted_monos if m.coeff != Fraction(0, 1))
def poly_long_division(self, other: Polynomial) -> tuple[Polynomial, Polynomial]:
"""Perform polynomial long division.
Args:
other: The divisor Polynomial.
Returns:
A tuple (quotient, remainder).
Raises:
ValueError: If other is not a Polynomial or is zero.
"""
if not isinstance(other, Polynomial):
raise ValueError("Can only divide by another Polynomial.")
if len(other.all_monomials()) == 0:
raise ValueError("Cannot divide by zero polynomial.")
quotient = Polynomial([])
remainder = self.clone()
divisor_monos = sorted(
other.all_monomials(),
key=lambda m: sorted(m.variables.items(), reverse=True),
reverse=True,
)
divisor_lead = divisor_monos[0]
while remainder.all_monomials() and max(
remainder.variables(), default=-1
) >= max(other.variables(), default=-1):
remainder_monos = sorted(
remainder.all_monomials(),
key=lambda m: sorted(m.variables.items(), reverse=True),
reverse=True,
)
remainder_lead = remainder_monos[0]
if not all(
remainder_lead.variables.get(var, 0)
>= divisor_lead.variables.get(var, 0)
for var in divisor_lead.variables
):
break
lead_quotient = remainder_lead / divisor_lead
quotient = quotient + Polynomial([lead_quotient])
remainder = remainder - (Polynomial([lead_quotient]) * other)
return quotient, remainder