[perl-python] generic equivalence partition

John Machin sjmachin at lexicon.net
Thu Feb 24 22:33:50 EST 2005


On Thu, 24 Feb 2005 17:48:47 -0800, Bryan <belred at gmail.com> wrote:

>Xah Lee wrote:
>> another functional exercise with lists.
>> 
>> Here's the perl documentation. I'll post a perl and the translated
>> python version in 48 hours.
>> 
>> =pod
>> 
>> parti(aList, equalFunc)
>> 
>> given a list aList of n elements, we want to return a list that is a
>> range of numbers from 1 to n, partition by the predicate function of
>> equivalence equalFunc. (a predicate function is a function that
>> takes two arguments, and returns either True or False.)

[snip]

>> example:
>> parti([['x','x','x','1'],
>> ['x','x','x','2'],
[snip]
>> ['x','x','x','5']], sub {$_[0]->[3] == $_[1]->[3]} )
>> 
>> returns
>>  [[1],['2','3','4'],['5'],['6'],['7','8']];
>> 
>> =cut
>> 
>> In the example given, the input list's elements are lists of 4
>> elements, and the equivalence function is one that returns True if the
>> last item are the same.
>
[snip]

>> 
>
>this is the first thing that came to my mind.  i'm sure there are more clever 
>ways to do this.
>
>elements = [['x', 'x', 'x', '1'],
[snip]
>             ['x', 'x', 'x', '5']]
>pos = {}
>
>for i, element in enumerate(elements):
>     pos.setdefault(element[-1], []).append(i+1)
>
>p = pos.values()
>p.sort()
>[[1], [2, 3, 4], [5], [6], [7, 8]]
>
>

Bryan: Bzzzt. Xah was proposing a GENERAL function. You have HARDWIRED
his (simplistic) example.

Xah: Bzzzt. Too close to your previous exercise.







More information about the Python-list mailing list