% is not an operator [was Re: Verbose and flexible args and kwargs syntax]
Terry Reedy
tjreedy at udel.edu
Wed Dec 14 15:57:40 EST 2011
On 12/14/2011 5:09 AM, Eelco wrote:
> Arguably, the most elegant thing to do is to define integer division
> and remainder as a single operation;
It actually is, as quotient and remainder are calculated together. The
microprocessors I know of expose this (as does Python). 'a divmod b'
puts the quotient in one register and the remainder in another. If you
ask for just one of the two values, both are calculated and one is
grabbed while the other is returned.
> which is not only the logical
> thing to do mathematically, but might work really well
> programmatically too.
>
> The semantics of python dont really allow for this though. One could
> have:
>
> d, r = a // b
>>> a,b = divmod(10,3)
>>> a,b
(3, 1)
With CPython, int.__divmod__ lightly wraps and exposes the processor
operation.
> But it wouldnt work that well in composite expressions; selecting the
> right tuple index would be messy and a more verbose form would be
> preferred.
That is why we have
>>> a == 10 // 3
True
>>> b == 10 % 3
True
In both cases, I believe CPython calls int.__divmod__ (or the lower
level equivalent) to calculate both values, and one is returned while
the other is ignored. It it the same when one does long division by hand.
> However, performance-wise its also clearly the best
> solution, as one often needs both output arguments and computing them
> simultaniously is most efficient.
As indicated above, there is really no choice but to calculate both at
once. If one needs both a//b and a%b, one should explicitly call divmod
once and save (name) both values, instead of calling it implicitly twice
and tossing half the answer each time.
--
Terry Jan Reedy
More information about the Python-list
mailing list