QfdZddlmZddlZddlZddlZddlZddlZddlZdgZ ejjZ ejjZejddZej"dej$ej&zZd d Zd Zej"d ej.ej$zj0ZGd dej4Zy)z/Fraction, infinite-precision, rational numbers.DecimalNFractioni@)maxsizec t|dt}ttt||z}|dk\r|n| }|dk(rdS|S#t$r t }Y$wxYw)Nr)pow_PyHASH_MODULUShashabs ValueError _PyHASH_INF) numerator denominatordinvhash_results 0/opt/alt/python312/lib64/python3.12/fractions.py_hash_algorithmrse2;O4(T#i.)D011nU5&F22)6)+ sAAAa \A\s* # optional whitespace at the start, (?P[-+]?) # an optional sign, then (?=\d|\.\d) # lookahead for digit or .digit (?P\d*|\d+(_\d+)*) # numerator (possibly empty) (?: # followed by (?:\s*/\s*(?P\d+(_\d+)*))? # an optional denominator | # or (?:\.(?P\d*|\d+(_\d+)*))? # an optional fractional part (?:E(?P[-+]?\d+(_\d+)*))? # and optional exponent ) \s*\Z # and optional whitespace to finish c|dk\r |d|zz}n |d| zz}t||dz z|\}}|dk(r |dzdk(r|dz}|r|dkn|dk}|t|fS)aMRound a rational number to the nearest multiple of a given power of 10. Rounds the rational number n/d to the nearest integer multiple of 10**exponent, rounding to the nearest even integer multiple in the case of a tie. Returns a pair (sign: bool, significand: int) representing the rounded value (-1)**sign * significand * 10**exponent. If no_neg_zero is true, then the returned sign will always be False when the significand is zero. Otherwise, the sign reflects the sign of the input. d must be positive, but n and d need not be relatively prime. r r )divmodr )ndexponent no_neg_zeroqrsigns r_round_to_exponentr"Js|1} R\ R(] !qAv, "DAqAv!a%1* R1q5QUD Q<c|dk(rddd|z fStt|t|}}t|t|z ||kz}||z }t|||\}}tt||dzk(r |dz}|dz }|||fS)aRound a rational number to a given number of significant figures. Rounds the rational number n/d to the given number of significant figures using the round-ties-to-even rule, and returns a triple (sign: bool, significand: int, exponent: int) representing the rounded value (-1)**sign * significand * 10**exponent. In the special case where n = 0, returns a significand of zero and an exponent of 1 - figures, for compatibility with formatting. Otherwise, the returned significand satisfies 10**(figures - 1) <= significand < 10**figures. d must be positive, but n and d need not be relatively prime. figures must be positive. rFrr)strr lenr") rrfiguresstr_nstr_dmrr! significands r_round_to_figuresr,gs" AvaW$$s1v;A5E E SZ5E>2A7{H*1a:D+ 3{ ! + A  h &&r#a (?: (?P.)? (?P[<>=^]) )? (?P[-+ ]?) (?Pz)? (?P\#)? # A '0' that's *not* followed by another digit is parsed as a minimum width # rather than a zeropad flag. (?P0(?=[0-9]))? (?P0|[1-9][0-9]*)? (?P[,_])? (?:\.(?P0|[1-9][0-9]*))? (?P[eEfFgG%]) ceZdZdZdZd,fd ZedZedZefdZ dZ dZ d-d Z e d Ze d Zd Zd ZdZdZdZeeej,\ZZdZeeej4\ZZdZeeej<\ZZ dZ!ee!ejD\Z#Z$dZ%ee%ejL\Z'Z(dZ)ee)e*\Z+Z,dZ-ee-ej\\Z/Z0dZ1dZ2dZ3dZ4dZ5ejlfdZ7dZ8dZ9dZ:d.d Z;d!Zd$Z?d%Z@d&ZAd'ZBd(ZCd)ZDd*ZEd+ZFxZGS)/ra]This class implements rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. Fractions can also be constructed from: - numeric strings similar to those accepted by the float constructor (for example, '-2.3' or '1e10') - strings of the form '123/456' - float and Decimal instances - other Rational instances (including integers)  _numerator _denominatorcBtt| |}|t|tur||_d|_|St|tjr$|j|_|j|_|St|ttfr|j\|_|_|St|trt j#|}|t%d|zt |j'dxsd}|j'd}|r t |}nd}|j'd}|r6|j)dd}d t+|z}||zt |z}||z}|j'd }|r"t |}|d k\r |d |zz}n |d | zz}|j'd d k(r| }nt-dt|tcxur t|urnnnrt|tjrMt|tjr3|j|jz|j|jz}}n t-d|d k(rt/d|zt1j2||} |d kr| } || z}|| z}||_||_|S)aConstructs a Rational. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. Examples -------- >>> Fraction(10, -8) Fraction(-5, 4) >>> Fraction(Fraction(1, 7), 5) Fraction(1, 35) >>> Fraction(Fraction(1, 7), Fraction(2, 3)) Fraction(3, 14) >>> Fraction('314') Fraction(314, 1) >>> Fraction('-35/4') Fraction(-35, 4) >>> Fraction('3.1415') # conversion from numeric string Fraction(6283, 2000) >>> Fraction('-47e-2') # string may include a decimal exponent Fraction(-47, 100) >>> Fraction(1.47) # direct construction from float (exact conversion) Fraction(6620291452234629, 4503599627370496) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(Decimal('1.47')) Fraction(147, 100) rz Invalid literal for Fraction: %rnum0denomdecimal_rexprr!-z2argument should be a string or a Rational instancez+both arguments should be Rational instancesFraction(%s, 0))superr__new__typeintr/r0 isinstancenumbersRationalrrfloatras_integer_ratior%_RATIONAL_FORMATmatchrgroupreplacer& TypeErrorZeroDivisionErrormathgcd) clsrrselfr*r4r5scaler8g __class__s rr<zFraction.__new__s>Xs+C0  I#%"+$%! Iw'7'78"+"5"5$-$9$9! Iw'785>5O5O5Q2!2 Is+$**959$%G%.&/00 5#6 ("%e*K"#Kggi0G")//#r": "CL 0$-$5G $D #u, ''%.C!#h!8%S0I'2t83K776?c)!* I !9::)_ 8tK'8 8 G$4$45 {G$4$4 5##k&=&==%% (=(==#I 12 2 ! #$5 $AB B HHY , ?Aa  #' r#c t|tjr||St|ts1t |j d|dt |j d|j|jS)zConverts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). z%.from_float() only takes floats, not  ()) r?r@IntegralrBrH__name__r=_from_coprime_intsrC)rLfs r from_floatzFraction.from_float#sm a)) *q6MAu% \\1d1g.>.>@A A%s%%q'9'9';<rHrUr=rVrC)rLdecrs r from_decimalzFraction.from_decimal1st $ c7++ ,#c(#CC)sDI$6$689 9&s%%s';';'=>>r#cJtt| |}||_||_|S)zConvert a pair of ints to a rational number, for internal use. The ratio of integers should be in lowest terms and the denominator should be positive. )r;rr<r/r0)rLrrobjrPs rrVzFraction._from_coprime_ints=s*Hc*3/"& r#c |jdk(S)z*Return True if the Fraction is an integer.rr0rMs r is_integerzFraction.is_integerIs  A%%r#c2|j|jfS)zReturn a pair of integers, whose ratio is equal to the original Fraction. The ratio is in lowest terms and has a positive denominator. r.r`s rrCzFraction.as_integer_ratioMs !2!233r#c|dkr td|j|kr t|Sd\}}}}|j|j}} ||z}|||zz} | |kDrn|||||zz| f\}}}}||||zz }}/||z |z} d|z|| |zzz|jkrtj ||Stj || |zz|| |zzS)aWClosest Fraction to self with denominator at most max_denominator. >>> Fraction('3.141592653589793').limit_denominator(10) Fraction(22, 7) >>> Fraction('3.141592653589793').limit_denominator(100) Fraction(311, 99) >>> Fraction(4321, 8765).limit_denominator(10000) Fraction(4321, 8765) rz$max_denominator should be at least 1)rrrr)rr0rr/rV) rMmax_denominatorp0q0p1q1rraq2ks rlimit_denominatorzFraction.limit_denominatorTs@ Q CD D    /D> !#BB 1 111AAbDBO#R"Wb0NBBa!eqA R " $ Q31R4=D-- -..r26 6..r!B$w1R4@ @r#c|jSN)r/rjs rrzFraction.numerators ||r#c|jSror_rps rrzFraction.denominators ~~r#ch|jjd|jd|jdS)z repr(self)(z, rS)rPrUr/r0r`s r__repr__zFraction.__repr__s*#~~66#0A0AC Cr#c|jdk(rt|jS|jd|jS)z str(self)r/)r0r%r/r`s r__str__zFraction.__str__s4    !t' '"oot/@/@A Ar#c  !|s t|St|}|$td|dt|j|d*|d%td|dt|jd|dxsd}|dxsd }|d d k(rd n|d }t |d }t |d}t |d}t |dxsd} |d!t |dxsd} |d} | dvxr| } | } | dvrdnd}| dvr7| }| dk(r|dz}t|j|j||\}}d}| }nY| dvr t| dn| dz}t|j|j|\}}}| dvxs|dkDxs||zd k}|r|dz n| }| dk(rd}n|r |||zd!}nd }|d|dzd"}|rd n|}|dt||z  |t||z d}| r|jd}| r|sd nd#}||z|z}|r8| t|z t|z } j!r d$|zd%zdzn| !rIdt dz d$zz} d|d j !fd&t!|t d$Dz |z}|| t|z t|z z}|d k(r||z|zS|d'k(r||z|zS|d(k(rt|dz}|d||z|z||dzS||z|zS))zAFormat this fraction according to the given format specification.NzInvalid format specifier z for object of type alignzeropadz0; can't use explicit alignment when zero-paddingfill >r!r9r7ralt minimumwidthr3 thousands_sep precision6presentation_typegGEFGEezfF%%rdFreErz+03dr.c34K|]}||dzzyw)rN).0posleadingrs r z&Fraction.__format__..s)4r"r/r0maxr,r&rstripzfilljoinrange)"rM format_specrEr{rypos_signralternate_formrzrrr trim_zeros trim_pointexponent_indicatorrnegativer+ scientific point_posr'suffixdigitsr! frac_part separatortrailing min_leading first_posbodypaddinghalfrrs" @@r __format__zFraction.__format__st9 4K@ =+K?;&&*4j&9&9%<> 7^ 'E),<,H+K?;&&*4j&9&9%<=AA  V}#g%#v#-25=5/0 eEl+uY'(507C8 o. k*1c2 !"56&$.E~3E '' $5$>SC  %!zH C'A $6!2!2Hk%K !HkJ!I%,Iq!]  /@!2!2G/= +Hk8"T),a<,g%+  (2! yI  #F *+Hy,@+FGFF )a-12 sH23v;233v;245 !((-I$YBC y(61 &T2S]BKmm,9K1$q({G S\A-22Ijy)BGG4 CL!<4-G!,T2SY>? C<T>D( ( c\$;( ( c\w<1$D5D>D(4/'$%.@ @'>D( (r#cfd}djzdz|_j|_fd}djzdz|_j|_||fS)aGenerates forward and reverse operators given a purely-rational operator and a function from the operator module. Use this like: __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) In general, we want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. In Fraction, that means that we define __add__ and __radd__ as: def __add__(self, other): # Both types have numerators/denominator attributes, # so do the operation directly if isinstance(other, (int, Fraction)): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) # float and complex don't have those operations, but we # know about those types, so special case them. elif isinstance(other, float): return float(self) + other elif isinstance(other, complex): return complex(self) + other # Let the other type take over. return NotImplemented def __radd__(self, other): # radd handles more types than add because there's # nothing left to fall back to. if isinstance(other, numbers.Rational): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) elif isinstance(other, Real): return float(other) + float(self) elif isinstance(other, Complex): return complex(other) + complex(self) return NotImplemented There are 5 different cases for a mixed-type addition on Fraction. I'll refer to all of the above code that doesn't refer to Fraction, float, or complex as "boilerplate". 'r' will be an instance of Fraction, which is a subtype of Rational (r : Fraction <: Rational), and b : B <: Complex. The first three involve 'r + b': 1. If B <: Fraction, int, float, or complex, we handle that specially, and all is well. 2. If Fraction falls back to the boilerplate code, and it were to return a value from __add__, we'd miss the possibility that B defines a more intelligent __radd__, so the boilerplate should return NotImplemented from __add__. In particular, we don't handle Rational here, even though we could get an exact answer, in case the other type wants to do something special. 3. If B <: Fraction, Python tries B.__radd__ before Fraction.__add__. This is ok, because it was implemented with knowledge of Fraction, so it can handle those instances before delegating to Real or Complex. The next two situations describe 'b + r'. We assume that b didn't know about Fraction in its implementation, and that it uses similar boilerplate code: 4. If B <: Rational, then __radd_ converts both to the builtin rational type (hey look, that's us) and proceeds. 5. Otherwise, __radd__ tries to find the nearest common base ABC, and fall back to its builtin type. Since this class doesn't subclass a concrete type, there's no implementation to fall back to, so we need to try as hard as possible to return an actual value, or the user will get a TypeError. ct|tr ||St|tr|t|St|trt||St|trt ||St Sro)r?rr>rBcomplexNotImplemented)rjbfallback_operatormonomorphic_operators rforwardz-Fraction._operator_fallbacks..forwardesq!X&+Aq11As#+Ax{;;Au%(q155Aw'(Q77%%r#__c<t|tjrt||St|tjrt |t |St|tj rt|t|StSro) r?r@rArRealrBComplexrr)rrjrrs rreversez-Fraction._operator_fallbacks..reversessp!W--.+HQK;;Aw||,(q58<<Aw/(WQZ@@%%r#__r)rU__doc__)rrrrs`` r_operator_fallbackszFraction._operator_fallbackssi` & "3"<"<? UHUBG,,,r#c|j|j}}t|j|z|j|zz||zS)za % b)rrr)rjrrrs r_modz Fraction._mods; Br)akkB.>?bIIr#ct|tjr|jdk(r|j}|dk\r0t j |j|z|j|zS|jdkDr2t j |j| z|j| zS|jdk(rtd|j| zzt j |j | z|j | zSt|t|zSt|ttfrt||zStS)za ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the result will be rational. rrr:) r?r@rArrrrVr/r0rIrBrr)rjrpowers r__pow__zFraction.__pow__!s8 a)) *}}! A:#66q||u7L78~~7NPP\\A%#66q~~%7O78||v7MOO\\Q&+,=,-NNuf,D-EFF$66UF7R9: 5&7PRR Qx58++ E7+ ,8q= ! !r#c.|jdk(r|jdk\r||jzSt|tjr#t |j |j|zS|jdk(r||jzS|t|zS)za ** brr) r0r/r?r@rArrrrB)rrjs r__rpow__zFraction.__rpow__As{ >>Q 1<<1#4 $ $ a)) *AKK71< < >>Q  $ $E!H}r#cVtj|j|jS)z++a: Coerces a subclass instance to FractionrrVr/r0rps r__pos__zFraction.__pos__Os**1<<HHr#cXtj|j |jS)z-arrps r__neg__zFraction.__neg__Ss**ALL=!..IIr#chtjt|j|jS)zabs(a))rrVr r/r0rps r__abs__zFraction.__abs__Ws"**3q||+>1 1r#c4|j|jzS)z math.floor(a)r.rps r __floor__zFraction.__floor__is||q~~--r#c8|j |jz S)z math.ceil(a)r.rps r__ceil__zFraction.__ceil__ms,,!..011r#c&|K|j}t|j|\}}|dz|kr|S|dz|kDr|dzS|dzdk(r|S|dzSdt|z}|dkDrt t ||z|St t ||z |zS)z?round(self, ndigits) Rounds half toward even. rdrrr)r0rr/r rround)rMndigitsrfloor remaindershifts r __round__zFraction.__round__rs ?!!A%dooq9 E91}q  Q"qy a qy CL  Q;E$,/7 7E$,/%78 8r#cBt|j|jS)z hash(self))rr/r0r`s r__hash__zFraction.__hash__st0A0ABBr#ct|tur |j|k(xr|jdk(St |t j r4|j|jk(xr|j|jk(St |t jr|jdk(r |j}t |trCtj|stj|rd|k(S||j!|k(St"S)za == brr)r=r>r/r0r?r@rArrrimagrealrBrJisnanisinfrXrrs r__eq__zFraction.__eq__s 7c><<1$<1)< < a)) *LLAKK/4NNamm3 5 a )affkA a zz!} 1 axALLO++" !r#cft|tjr7||j|jz|j |j zSt|trKtj|stj|r |d|S|||j|StS)acHelper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. r) r?r@rAr/rr0rrBrJrrrXr)rMotherops r_richcmpzFraction._richcmps eW-- .doo(9(99''%//9; ; eU #zz% DJJu$5#u~%$ 677! !r#cB|j|tjS)za < b)roperatorltrs r__lt__zFraction.__lt__zz!X[[))r#cB|j|tjS)za > b)rrgtrs r__gt__zFraction.__gt__r r#cB|j|tjS)za <= b)rrlers r__le__zFraction.__le__r r#cB|j|tjS)za >= b)rrgers r__ge__zFraction.__ge__r r#c,t|jS)za != 0)rr/rps r__bool__zFraction.__bool__sALL!!r#cJ|j|j|jffSro)rPr/r0r`s r __reduce__zFraction.__reduce__s $2C2C DEEr#cvt|tk(r|S|j|j|jSror=rrPr/r0r`s r__copy__zFraction.__copy__. : !K~~doot/@/@AAr#cvt|tk(r|S|j|j|jSror)rMmemos r __deepcopy__zFraction.__deepcopy__rr#)rN)i@Bro)HrU __module__ __qualname__r __slots__r< classmethodrXr[rVrarCrmpropertyrrrtrwrrrradd__add____radd__rsub__sub____rsub__rmul__mul____rmul__rtruediv __truediv__ __rtruediv__rfloordiv __floordiv__ __rfloordiv__rr __divmod__ __rdivmod__rmod__mod____rmod__rrrrrindexrrrrrrrrr r rrrrrr __classcell__)rPs@rrrs(/IgR = = ? ?  &47ArC Br)hk b D,D(,,?GX D,D(,,?GX =,D(,,?GX1(!4D(:J:J KKN#6iARAR"SL-- 2'6BJ J ,D(,,?GX"@ IJN#..:2.2 94C"*",****"FB Br#)F)rr5r functoolsrJr@rresys__all__ hash_infomodulusr infr lru_cachercompileVERBOSE IGNORECASErDr"r,DOTALL fullmatchrrArrr#rrGs6  , --''mm w'*(*@2:: ZZ"-- !":$'R'1bjj2YY''Y$$| Bw| Br#