PEP 303: Extend divmod() for Multiple Divisors

Anton Vredegoor anton at vredegoor.doge.nl
Wed Jan 1 20:22:51 EST 2003


On Tue, 31 Dec 2002 17:06:16 +0000 (UTC), Thomas Bellman
<bellman+pep-divmod at lysator.liu.se> wrote:

>    A Python implementation of the new divmod() behaviour could look
>    like:
>
>        def divmod(dividend, *divisors):
>            modulos = ()
>            q = dividend
>            while divisors:
>                q,r = q.__divmod__(divisors[-1])
>                modulos = (r,) + modulos
>                divisors = divisors[:-1]
>            return (q,) + modulos
>

This would make a short permutation algorithm possible. Very
seductive. Maybe it's too good and we shouldn't do it? :-)

I have experimented with divmod too, and turned it into a kind of
generalized threshold index finder.

The divisors argument would become a function that would generate a
sequence. Divmod would return the index of the element just before the
element that is bigger than dividend, and the difference between this
element and dividend.

If the sequence would consist of a list of numbers that increases by a
constant amount, the original divmod would be mimicked.

I think that what is proposed in PEP 303 has the merit of being very
useful at a short term. In the long term it might become a hindrance
to other interpretations of what a divmod really should be. It seems
not to preclude the generalization described above because the ideas
are orthogonal. I am in favor of this PEP.

+1

Regards,
		Anton.

Here's the short permutation algorithm for PEP 303:

def perm(i,s):
    L = list(s)
    return "".join([L.pop(x) for x in\
        divmod(i,*range(len(L)-1,0,-1))])
    
def test():
    for i in range(24):
         print perm (i,"abcd")

if __name__=='__main__':
    test()





More information about the Python-list mailing list