maximum() efficency

Steve R. Hastings steve at hastings.org
Mon Mar 27 14:16:05 EST 2006


On Mon, 27 Mar 2006 07:50:01 -0800, Arne Ludwig wrote:
> Just for completeness: The functions in Steve's original post named
> maximum calculate the minimum.

Er, yes.  I benchmarked them but clearly I should have function-tested
them as well.



Here is, I hope, my last word on maximum().  It figures out whether it got
an iterator or a list, and does the right thing.  I believe it will
compile and run correctly whether your version of Python has iterators or
not.  And, it doesn't compute the minimum.



def maximum(cmp, seq):
  """
  Return maximum value of seq, as chosen by provided cmp() function.

  If seq contains multiple maximal values, return the last one.

  Arguments:
    cmp -- function reference; function should return values with the
      same semantics as Python's cmp() function.
    seq -- any sequence (a list or an iterator).  If seq is empty, this
      function will raise ValueError.
  """
  # is it a list?
  if hasattr(seq, "__getitem__"):
    if len(seq) == 0:
      raise ValueError, "seq must contain at least 1 element"

    maxval = seq[0]
    for v in seq:
        if cmp(maxval, v) <= 0:
          maxval = v
    return maxval


  # is it an iterator?
  if hasattr(seq, "__iter__") and hasattr(seq, "next"):
    try:
      maxval = seq.next()
    except StopIteration:
      raise ValueError, "seq must contain at least 1 element"

    for v in seq:
        if cmp(maxval, v) <= 0:
          maxval = v
    return maxval


  raise TypeError, "seq must be a list or an iterator"



-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list