A use for integer quotients

Terry Reedy tjreedy at home.com
Sun Jul 22 20:55:58 EDT 2001


During the debate on changing int/int to give a float result, some
proponents appeared to question the usefulness of integer quotients.
Opponents of the change gave calculation of array indexes, including
graphics pixel coordinates, and 'combinatorics' as example uses.  I
here present an particular example of a combinatorial use extracted
from the recent thread on partitions.

Problem: what are the ways to distribute n items among k unlabelled
bins, with each bin getting at least 1 item.

Extreme uneven answer: put n-(k-1) items in 1 bin and 1 item in each
of the other k-1 bins.  The largest bin in a partition has at most
n-k+1 items.

Extreme even answer: put n/k items in each bin and 1 more in each of
n%k bins.  The largest bin in a partition has at least (n/k + (n%k
>=1)) items, which is more efficiently calculated as  (n+(k-1))/k.  If
we use a descending range, then we subtract 1 to get (n-1)/k for use
in
range((n-k+1), (n-1)/k, -1).

With these limits on the largest bin and the additional constraint
that bins be filled in monotonically decreasing size order, there is a
straightforward recursive algorithm, which I posted in the partition
thread.  While there are other algorithms (some posted), this one, at
least, which is pretty easy to understand, depends on
quotient-remainder thinking to get the proper lower limit.

--------------------

What does this have to do with PEP238 and the proposed change?  When I
thought some people were arguing simply to change int/int to give a
float (with no new alternative for an int result), I was adamantly
opposed.  I really want Python to remain 'executable pseudocode' so I
and others can write and publish such algorithms in Python with
concise standard or near-standard syntax, without resort to a
non-standard circumlocution like divmod((n+(k-1)), k)[0]  or a
distracting and inefficient roundtrip to float and back.

When Guido said he really wanted to make a change *and* that he would
look favorably on an infix substitute, I muted my opposition and wrote
'Language Change and Code Breaks' to clarify what was needed to make
such a syntax replacement successful.  I will not mind too much
writing (n+(k-1))//k, which is my preferred alternative.  It should
not be too hard to explain to a non-Python audience that '/' is
calculator decimal-result division while '//' is truncating
whole-number-quotient division.

Terry J. Reedy






More information about the Python-list mailing list