CS21 In Class: week 10

lists of lists (2D lists), list algorithms: sorting

Setting up a subdirectory for week 10 in-class work


cd into your cs21/class/ subdirectory and create a new directory named 'week10', then cd into that directory:
$ cd cs21/class                     # cd into your cs21/class subdirectory
$ pwd	          
  /home/your_user_name/cs21/class

$ mkdir week10                      # make a subdirectory named week10   
$ cd week10                         # cd into it
$ pwd           
  /home/your_user_name/cs21/class/week10

Now copy over all the files from my public/cs21/week10 directory into your week10 directory (remember to add the dot as the destination of the cp command). From your week10 directory:

$ cp ~newhall/public/cs21/week10/* .

Weekly In-class Examples

This week we are going to look at lists of lists and some operations on lists.

Using the starting point file list_algs.py, we are going to:

  1. Look at linear and binary search.
  2. add some other functions.
  3. In main, there is some commented out timing code. You could try uncommenting it to see what it does.

A note on comparing string values

In Python, you can use the relational operators (<,<=,>,>=, ==, !=) to compare the value of two strings:
s1 = "hello"
s2 = raw_input("Enter a string: ")
if(s1 == s2):
   print("%s is equal to %s" % (s1,s2))
elif(s1 > s2):
   print("%s is greater than %s" % (s1,s2))
else:
   print("%s is less than %s" % (s1,s2))
Remember that strings are compared by their ascii values (numeric encodings of each character). You can see the ascii encodings by running:
man ascii           # use the arrow keys to navigate, and 'q' to quit

Never memorize the ascii encoding, but it is important to know that the encodings for 'a' to 'z' are contiguous, as are 'A' to 'Z' and '0' to '9'. Internally, python uses the ascii encoding of characters to compare strings. For example, for the following expression:

"anteater" == "anywhere"
Python first compares the ascii values the first character in each string (97 for 'a' to 97 for 'a'). Since they are equal, it then compares the ascii value of the second character in each string (110 for 'n' to 110 for 'n'). Since they are equal, it then compares the ascii value of the third character in each string (116 for 't' to 121 for 'y'). Since the ascii values are not equal, python evaluates the expression to False.

The ascii encoding also explains why the following relational expressions evaluate to True:

"Zoo" < "ant"   # ascii value for upper-case 'Z' is smaller than for lower-case 'a'
"zoo" > "ant"   # ascii value for lower-case 'z' is larger  than for lower-case 'a'

str and list documentation