Mainly Tech projects on Python and Electronic Design Automation.

Saturday, February 23, 2008

Length Sorts

Andre Roberge just informed me of a site with ninety nine Prolog problems. A quick scan and I got as far as P28 before thinking that I would like to try it. so here is my solution to P28. Note that there is much more comments than code, I decided to cut-n-paste my command line scribblings as an explanation of the second function, rather like doctests.

In doing this, I also learned that you could not take the len of a groupby object :-)

The code:

(Note: I would like to make this available under the Python License version 2.4.2)

''' \
Length sorts. From P28

A code kata

Answer in Python (C) Donald 'Paddy' McCarthy, Feb. 23, 2008

from itertools import groupby

def length_sort(lst):
''' \
Sort a list-of-lists on sub-list length


>>> l = [['a','b','c'],['d','e'],['f','g','h'],['d','e'],['i','j','k','l'],['m','n'],['o']]
>>> length_sort(l)
[['o'], ['d', 'e'], ['d', 'e'], ['m', 'n'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l']]

return sorted(lst, key=len)

def length_freq_sort(lst):
''' \
Sort a list-of-lists on frequency of sub-lists length


>>> l = [['a','b','c'],['d','e'],['f','g','h'],['d','e'],['i','j','k','l'],['m','n'],['o']]
>>> length_freq_sort(l)
[['i', 'j', 'k', 'l'], ['o'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['d', 'e'], ['d', 'e'], ['m', 'n']]

## Comments give example working out

# >>> lst = [['a','b','c'],['d','e'],['f','g','h'],['d','e'],['i','j','k','l'],['m','n'],['o']]
lengths = sorted(len(x) for x in lst)
# >>> lengths
# [1, 2, 2, 2, 3, 3, 4]
# >>> [(a,len(list(b))) for a,b in groupby(lengths)]
# [(1, 1), (2, 3), (3, 2), (4, 1)]
# >>> dict([(a,len(list(b))) for a,b in groupby(lengths)])
# {1: 1, 2: 3, 3: 2, 4: 1}
len2freq = dict([(a,len(list(b))) for a,b in groupby(lengths)])

return sorted(lst, key=lambda x: len2freq[len(x)])


  1. Superfluous lambda alert: sorted(lst, key=len) works just as well.

  2. Hi Paddy,

    Can I adapt your solution when I get around to writing up problem 28?
    (I'd like to make them available with no copyright restrictions...)

  3. Will the Python license suffice.

    - Paddy.

  4. Superfluous def alert, too.

    length_sort = functools.partial(sorted, key=len)

    1. Understand the question to attempt a correct answer.



Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

Blog Archive