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

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(defaultmax=None):  maxvalue = defaultmax  while 1:  value = max(yield maxvalue)  if maxvalue is None or value>  maxvalue:  maxvalue = 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 "", line 1, in 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 RunningMin(outvalue=None):  while 1:  invalue = yield outvalue  if invalue is not None:  if outvalue is None:  outvalue = xmin(invalue)  else:  outvalue = xmin(outvalue, xmin(invalue)) Or for your class... def xmax(value):  try:  return max(value)  except TypeError:  return max([value]) class RunningMax(RunningCalc):  def init(self):  self.maxvalue = None  def feed(self, value):  if value is not None:  if self.maxvalue is None:  self.maxvalue = xmax(value)  else:  self.maxvalue = xmax(self.maxvalue, 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