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 https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ 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
Example
>>> 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
Example
>>> 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)])
Superfluous lambda alert: sorted(lst, key=len) works just as well.
ReplyDeleteThanks Peter.
ReplyDeleteHi Paddy,
ReplyDeleteCan I adapt your solution when I get around to writing up problem 28?
(I'd like to make them available with no copyright restrictions...)
Will the Python license suffice.
ReplyDelete- Paddy.
Superfluous def alert, too.
ReplyDeletelength_sort = functools.partial(sorted, key=len)
Understand the question to attempt a correct answer.
Delete