How about adding rational fraction to Python?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Feb 27 19:49:41 EST 2008
On Tue, 26 Feb 2008 20:55:14 -0800, Paul Rubin wrote:
> Mark Dickinson <dickinsm at gmail.com> writes:
>> def mean(number_list):
>> return sum(number_list)/len(number_list)
>>
>> If you pass a list of floats, complex numbers, Fractions, or Decimal
>> instances to mean() then it'll work just fine. But if you pass
>> a list of ints or longs, it'll silently return the wrong result.
>
> So use: return sum(number_list) / float(len(number_list)) That makes it
> somewhat more explicit what you want. Otherwise I wouldn't be so sure
> the integer result is "wrong".
Oh come on. With a function named "mean" that calculates the sum of a
list of numbers and then divides by the number of items, what else could
it be?
You can always imagine corner cases where some programmer, somewhere, has
some bizarre need for a mean() function that truncates when given a list
of integers but not when given a list of floats. Making that the default
makes life easy for the 0.1% corner cases and life harder for the 99.9%
of regular cases, which is far from the Python philosophy.
It's better to reverse the burden, as Python does. Not that it is much
harder to write truncating_mean_for_ints_but_not_floats(): just use
the // int operator instead of /. At which point somebody will chime up
that int division gives the wrong result with one negative operand,
because in *their* opinion it should truncate rather than round to floor:
>>> 1//3
0
>>> -1//3 # expect 0
-1
--
Steven
More information about the Python-list
mailing list