PEP 303: Extend divmod() for Multiple Divisors

Andrew Dalke adalke at mindspring.com
Tue Dec 31 14:38:56 EST 2002


Thomas Bellman wrote:
> I was hoping that the reason for the order of the divisors was
> made clear in the Rationale section.  Basically, the order just
> *felt* right when using it.  divmod(seconds, 7, 24, 60, 60)
> came more naturaly to me than divmod(seconds, 60, 60, 24, 7).

I agree with Martin, I have a preference for the order to be
the other way.  It comes from thinking about "okay, divide by
seconds then minutes then hours then days then weeks" like I
would if I was using divmod by hand.

OTOH, I think your preference comes from the way you want
the output to read, since it's easier to think of the larger
terms before the smaller ones, as with

   w, d, h, m, s = divmod(seconds, 7, 24, 60, 60)

compare that to the alternates of

   s, m, h, d, w = divmod(seconds, 60, 60, 24, 7)
   w, d, h, m, s = divmod(seconds, 60, 60, 24, 7)


Looking at the standard library, I see use case for chained
divmods which may help, since it doesn't bias matters
by using well-known variable names or values

         a, x = divmod(a, 30268)
         a, y = divmod(a, 30306)
         a, z = divmod(a, 30322)
         self._seed = int(x)+1, int(y)+1, int(z)+1

The way I would expect to see it rewritten is

    x, y, z, a = divmod(a, 30268, 30306, 30322)

However, you would want it rewritten

    a, z, y, x = divmod(a, 30322, 30306, 30268)

This seems backwards to me.

 >>> start = 123654789555
 >>> a = start
 >>> a, x = divmod(a, 30268)
 >>> a, y = divmod(a, 30306)
 >>> a, z = divmod(a, 30322)
 >>> x, y, z, a
(21115L, 24326L, 134L, 0L)
 >>> def new_divmod(dividend, *divisors):
...             modulos = ()
...             q = dividend
...             while divisors:
...                 q,r = q.__divmod__(divisors[-1])
...                 modulos = (r,) + modulos
...                 divisors = divisors[:-1]
...             return (q,) + modulos
...
 >>> new_divmod(start, 30268, 30306, 30322)
(0L, 134L, 17051L, 5845L)
 >>> new_divmod(start, 30322, 30306, 30268)
(0L, 134L, 24326L, 21115L)
 >>>


					Andrew
					dalke at dalkescientific.com




More information about the Python-list mailing list