Python primer - comments appreciated!

Thorsten Kampe thorsten at thorstenkampe.de
Tue Sep 10 02:14:35 CEST 2002


"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

    With the 'bool' parameter 'quotient_set' always returns two lists: the
    first  containing the 'true' items and the second containing the false
    ones. """
    if partition == 'bool':
    # Yes, I know about 'filter', but this returns just the 'true
    # elements'...
    
        # put this in one line?
        true_class  = []
        false_class = []

        for item in seq:
            if func(item):
                true_class.append(item)
            else:
                false_class.append(item)
        return [true_class, false_class]
        
    else:
        # put this in one line?
        quotient_set =         []
        representative_class = []

        for item in seq:
            representative = func(item)

            # "Try: seq.index(item)" is IMO rather ugly in a loop. But
            # it's even better than "if item in seq: seq.index(item)",
            # which goes twice through seq
            try:
                quotient_set_index = representative_class.index(representative)
            except ValueError:
                quotient_set.append([item])
                representative_class.append(representative)            
            else:
                # This somehow "inelegant", because all I want to do is:
                # "seq[index] = seq[index].append(item)" Suggestions?
                equivalence_class = quotient_set[quotient_set_index]
                equivalence_class.append(item)
                quotient_set[quotient_set_index] = equivalence_class
                
        return quotient_set
#v-

To get a feeling for what 'quotient_set' does, try:
>>> f = lambda x: x % 3
>>> quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

>>> quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f, 'bool')
[[1, 2, 4, 5, 7, 8], [3, 6, 9]]

#v+
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)]    
#v-



More information about the Python-list mailing list