Main.Lab10 History

Hide minor edits - Show changes to markup

March 29, 2010, at 01:17 PM MST by 10.84.44.110 -
Changed line 20 from:

key(x) is a function that extracts a value that is used for comparison out of the given element.

to:

key_comparison_function(x) is a function that extracts a value that is used for comparison out of the given element.

March 29, 2010, at 11:01 AM MST by 10.84.44.110 -
Changed line 27 from:
to:

More information about sorting is found on the Python wiki.

March 29, 2010, at 10:59 AM MST by 10.84.44.110 -
Changed lines 1-3 from:

Lab 9

Using a list's sort method

to:

Lab 9

Using a list's sort method

March 29, 2010, at 10:59 AM MST by 10.84.44.110 -
Added lines 1-27:

Lab 9

Using a list's sort method

In this lab we will look in more detail on how to use a list's sort method.

Your task is to do the following two things:

  • Sort a list of strings of the form first name, last name by the last name in increasing lexicographical order.
  • Sort a list of strings of the form first name, last name by the last name in decreasing lexicographical order.

Python's sort method takes additional arguments that will help you do this.

The general way to call the sort method is:

a.sort(cmp=comparison_function, key=key_extraction_function, reverse=boolean_value)

comparison_function(x,y) is a function that indicates what is the relative order of x and y: it should return a positive value if x is greater than y, a negative number if y is greater than x, and 0 if they are equal.

key(x) is a function that extracts a value that is used for comparison out of the given element. For example, if you want to sort a list of strings ignoring the case of the string you would do: s.sort(key = str.lower).

If you want to sort a list strings in reverse order ignoring their case: s.sort(key=str.lower, reverse = True)