Python primer - comments appreciated!

Terry Reedy tjreedy at udel.edu
Mon Sep 9 21:39:40 EDT 2002


"Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
news:aljdhe$1q63hj$1 at ID-77524.news.dfncis.de...
> "Python, anyone?"... Yep, this is my first one. Comments on
> style/readability and technique/flow appreciated!
>
> #v+
> def quotient_set(seq, func, partition='nonbool'):
>     """ partition <seq> into equivalence classes

To my mind, you should return a dictionary mapping each realized value
of func (assuming hashable)  to the list of items for which func has
that value.  In other words, result.values() would be the list of
equivalence classes.  Let caller toss away info of value defining
class.  In any case, using a dict to sort items into such classes
should be much faster that what you wrote.

def equiv_class(seq, func, part = 'nonbool'):
  if part == 'bool':
    result = {False:[], True:[]}
    for item in seq:
      result[bool(func(item))].append(item)
  else:
    result = {}
    for item in seq:
      result.setdefault(func(item),[]).append(item)
      # {}.setdefault(key,default) was added for just this sort of
usage
  return result

>>> f = lambda x: x % 3
>>> equiv_class([0,1,2,3,4,5,6,7,8,9],f)
{0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}
>>> equiv_class([0,1,2,3,4,5,6,7,8,9],f,part='bool')
{0: [0, 3, 6, 9], 1: [1, 2, 4, 5, 7, 8]}


> def set(seq):
>     """ make <seq> a true set by removing duplicates """
>     # Shortest way to do a 'null function'? 'None' doesn't work...
>     f = lambda x: x  # identity function
>
>     return [item[0] for item in quotient_set(seq, f)]

No, no.  If items are hashable, standard method is...

def set(seq):
  d = {}
  for item in seq:
    d[item] = 0
  return d.keys()

Terry J. Reedy






More information about the Python-list mailing list