@@ -438,28 +438,19 @@ def __floordiv__(self, other: Union[int, float, Fraction, Monomial]):
438
438
# def __truediv__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:
439
439
def __truediv__ (self , other : Union [int , float , Fraction , Monomial ]):
440
440
"""
441
- For Polynomials, only division by a monomial
442
- is defined.
443
-
444
- TODO: Implement polynomial / polynomial.
441
+ For Polynomial division, no remainder is provided. Must use poly_long_division() to capture remainder
445
442
"""
446
443
if isinstance (other , int ) or isinstance (other , float ) or isinstance (other , Fraction ):
447
444
return self .__truediv__ ( Monomial ({}, other ) )
448
445
elif isinstance (other , Monomial ):
449
446
poly_temp = reduce (lambda acc , val : acc + val , map (lambda x : x / other , [z for z in self .all_monomials ()]), Polynomial ([Monomial ({}, 0 )]))
450
447
return poly_temp
451
448
elif isinstance (other , Polynomial ):
452
- if Monomial ({}, 0 ) in other .all_monomials ():
453
- if len (other .all_monomials ()) == 2 :
454
- temp_set = {x for x in other .all_monomials () if x != Monomial ({}, 0 )}
455
- only = temp_set .pop ()
456
- return self .__truediv__ (only )
457
- elif len (other .all_monomials ()) == 1 :
458
- temp_set = {x for x in other .all_monomials ()}
459
- only = temp_set .pop ()
460
- return self .__truediv__ (only )
461
-
462
- raise ValueError ('Can only divide a polynomial by an int, float, Fraction, or a Monomial.' )
449
+ # Call long division
450
+ quotient , remainder = self .poly_long_division (other )
451
+ return quotient # Return just the quotient, remainder is ignored here
452
+
453
+ raise ValueError ('Can only divide a polynomial by an int, float, Fraction, Monomial, or Polynomial.' )
463
454
464
455
return
465
456
@@ -526,7 +517,59 @@ def subs(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, f
526
517
527
518
def __str__ (self ) -> str :
528
519
"""
529
- Get a string representation of
530
- the polynomial.
520
+ Get a properly formatted string representation of the polynomial.
521
+ """
522
+ sorted_monos = sorted (self .all_monomials (), key = lambda m : sorted (m .variables .items (), reverse = True ),
523
+ reverse = True )
524
+ return ' + ' .join (str (m ) for m in sorted_monos if m .coeff != Fraction (0 , 1 ))
525
+
526
+ def poly_long_division (self , other : 'Polynomial' ) -> tuple ['Polynomial' , 'Polynomial' ]:
531
527
"""
532
- return ' + ' .join (str (m ) for m in self .all_monomials () if m .coeff != Fraction (0 , 1 ))
528
+ Perform polynomial long division
529
+ Returns (quotient, remainder)
530
+ """
531
+ if not isinstance (other , Polynomial ):
532
+ raise ValueError ("Can only divide by another Polynomial." )
533
+
534
+ if len (other .all_monomials ()) == 0 :
535
+ raise ValueError ("Cannot divide by zero polynomial." )
536
+
537
+ quotient = Polynomial ([])
538
+ remainder = self .clone ()
539
+
540
+ divisor_monos = sorted (other .all_monomials (), key = lambda m : sorted (m .variables .items (), reverse = True ),
541
+ reverse = True )
542
+ divisor_lead = divisor_monos [0 ]
543
+
544
+ while remainder .all_monomials () and max (remainder .variables (), default = - 1 ) >= max (other .variables (),
545
+ default = - 1 ):
546
+ remainder_monos = sorted (remainder .all_monomials (), key = lambda m : sorted (m .variables .items (), reverse = True ),
547
+ reverse = True )
548
+ remainder_lead = remainder_monos [0 ]
549
+
550
+ if not all (remainder_lead .variables .get (var , 0 ) >= divisor_lead .variables .get (var , 0 ) for var in
551
+ divisor_lead .variables ):
552
+ break
553
+
554
+ lead_quotient = remainder_lead / divisor_lead
555
+ quotient = quotient + Polynomial ([lead_quotient ]) # Convert Monomial to Polynomial
556
+
557
+ remainder = remainder - (
558
+ Polynomial ([lead_quotient ]) * other ) # Convert Monomial to Polynomial before multiplication
559
+
560
+ return quotient , remainder
561
+
562
+ dividend = Polynomial ([
563
+ Monomial ({1 : 3 }, 4 ), # 4(a_1)^3
564
+ Monomial ({1 : 2 }, 3 ), # 3(a_1)^2
565
+ Monomial ({1 : 1 }, - 2 ), # -2(a_1)
566
+ Monomial ({}, 5 ) # +5
567
+ ])
568
+
569
+ divisor = Polynomial ([
570
+ Monomial ({1 : 1 }, 2 ), # 2(a_1)
571
+ Monomial ({}, - 1 ) # -1
572
+ ])
573
+
574
+ quotient = dividend / divisor
575
+ print ("Quotient:" , quotient )
0 commit comments