Python Sort Function

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


19 points

Hi there everyone,

Does anyone have a clue on an ideal function body for this script so that it will pass the doctest?

def sortstuff(mylist):
"""
>>> sortstuff([3, 5, 1, 9, 13, 2])
[1, 2, 3, 5, 9, 13]
>>> sortstuff(["one", "two", "three", "four"])
['four', 'one', 'three', 'two']
"""
 
# Function body will go here
 
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)

Cheers!



6 points

Should you not use Python sort? For example:

li=[1,9,2,3];
li.sort();
print li;

Note that sort is a method, and the list is changed in place.

Suppose you have a matrix, and you want to sort by second column. Example Solution:

li=[[2,6],[1,3],[5,4]]
li.sort(lambda x, y: cmp(x[1],y[1]))
print li; # prints [[1, 3], [5, 4], [2, 6]]

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.