Python primer - comments appreciated!

Thorsten Kampe thorsten at thorstenkampe.de
Tue Sep 10 17:54:31 EDT 2002


* Terry Reedy
> "Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
> news:aljdhe$1q63hj$1 at ID-77524.news.dfncis.de...
>> 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)

Using the 'bool' function and dictionaries makes my whole "if part == 
'bool'" branch superfluous - see below.

>      result.setdefault(func(item),[]).append(item)

To make every item hashable, I made this:
result.setdefault(repr(func(item)),[]).append(item)

>      # {}.setdefault(key,default) was added for just this sort of usage

Sorry, I just don't get it: your mixing (chaining?) a dict method and 
a list method as if it was a f(g(x)) and /it works/!?! Where is that 
documented? How is is that evaluated (left to right)?

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

Now this is: 
quotient_set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], lambda x: bool(x % 3))

(Mathematically spoken, the quotient set is the set of all equivalence 
classes induced by func, which is what we return)


Thorsten



More information about the Python-list mailing list