PEP 303: Extend divmod() for Multiple Divisors

Thomas Bellman bellman at lysator.liu.se
Thu Jan 2 16:32:21 EST 2003


Andrew Dalke <adalke at mindspring.com> wrote:

> 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)

Correct, I think the first version is easiest to think of and to
read.  The last version I think would be quite awkward to read,
since the result comes in the opposite order from the parameters:
you specify the number of days per week last, but the weeks and
days come out first.

There is also the matter of backward compatibility: divmod
currently returns the quotient first, and the remainder second.
For the sake of consistensy, one absolutely wants the quotient to
come first regardless of the number of divisors; doing otherwise
would be quite awful.  That rules out using the order

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

That actually leaves us with another alternative, which you
didn't suggest:

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

But that also feels weird to read.

>          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.

Yes, it might feel backwards.  However, reading more of the
code from the WhichmanHill generator in random.py, I get the
impression that there is no inherent meaning in the incoming
value a.  And the final value of a, after the three divmod()
calls, is just thrown away.

But yes, rewriting that code to use a generalized divmod() is
slightly less straightforward.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"God is real, but Jesus is an integer."      !  bellman @ lysator.liu.se
                                             !  Make Love -- Nicht Wahr!




More information about the Python-list mailing list