[Python-ideas] [Python-Dev] minmax() function returning (minimum, maximum) tuple of a sequence

Guido van Rossum guido at python.org
Fri Oct 15 04:14:02 CEST 2010


Why would you ever want to write min(1)? (Or min(x) where x is not iterable.)

--Guido

On Thu, Oct 14, 2010 at 7:09 PM, Ron Adam <rrr at ronadam.com> wrote:
>
>
> On 10/13/2010 07:13 PM, Tal Einat wrote:
>>
>> On Thu, Oct 14, 2010 at 1:14 AM, Nick Coghlan wrote:
>>>
>>> Why use feed() rather than the existing generator send() API?
>>>
>>> def runningmax(default_max=None):
>>>    max_value = default_max
>>>    while 1:
>>>        value = max(yield max_value)
>>>        if max_value is None or value>  max_value:
>>>            max_value = value
>>
>> I tried using generators for this and it came out very clumsy. For one
>> thing, using generators for this requires first calling next() once to
>> run the generator up to the first yield, which makes the user-facing
>> API very confusing. Generators also have to yield a value at every
>> iteration, which is unnecessary here. Finally, the feedMultiple
>> optimization is impossible with a generator-based implementation.
>
> Something I noticed about the min and max functions is that they treat
> values and iterable slightly different.
>
> # This works
>>>> min(1, 2)
> 1
>>>> min([1, 2])
> 1
>
>
> # The gotcha
>>>> min([1])
> 1
>>>> min(1)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: 'int' object is not iterable
>
>
> So you need a function like the following to make it handle single values
> and single iterables the same.
>
> def xmin(value):
>    try:
>        return min(value)
>    except TypeError:
>        return min([value])
>
> Then you can do...
>
> @consumer
> def Running_Min(out_value=None):
>    while 1:
>        in_value = yield out_value
>        if in_value is not None:
>            if out_value is None:
>                out_value = xmin(in_value)
>            else:
>                out_value = xmin(out_value, xmin(in_value))
>
>
> Or for your class...
>
> def xmax(value):
>    try:
>        return max(value)
>    except TypeError:
>        return max([value])
>
> class RunningMax(RunningCalc):
>    def __init__(self):
>        self.max_value = None
>
>    def feed(self, value):
>        if value is not None:
>            if self.max_value is None:
>                self.max_value = xmax(value)
>            else:
>                self.max_value = xmax(self.max_value, xmax(value))
>
>
> Now if they could handle None a bit better we might be able to get rid of
> the None checks too.  ;-)
>
> Cheers,
>   Ron
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list