I\'m currently new to python and got stuck at this question, can\'t seem to find the proper answer.
question:Given a list of words, return a list with the same words
Although Jochen Ritzel said you don't need cmp, this is actually a great use case for it! Using cmp you can sort by length and then alphabetically at the same time in half the time sorting twice would take!
def cmp_func(a, b):
# sort by length and then alphabetically in lowercase
if len(a) == len(b):
return cmp(a, b)
return cmp(len(a), len(b))
sorted_the_way_you_want = sorted(the_list, cmp=cmp_func)
Example:
>>> the_list = ['B', 'BB', 'AA', 'A', 'Z', 'C', 'D']
>>> sorted(the_list, cmp=cmp_func)
['A', 'B', 'C', 'D', 'Z', 'AA', 'BB']
Note, if your list is a mix of upper and lower case replace cmp(a, b) with cmp(a.lower(), b.lower()) as python sorts 'a' > 'Z'.
In python3 you'd need to be sorting objects with __lt__ style comparison functions defined or functools.cmp_to_key() which does that for you.