Lab 11: Binary Search, Exceptions, and 2D Lists

Goals

After the lab, you should be proficient at

  1. adapting binary search for use in another algorithm
  2. handling exceptions in Python
  3. creating and processing 2D lists

Linux

As usual, create a directory for the programs and output you develop in this lab.

You will want to copy the files from your lab10 directory so that you can extend your FaceSpace program.

Using the wc Command

Objective: Programming in Python

Extending the Social Network Program

If you haven't completed the Lab 10 social network program and you don't expect to finish it, you can use my solution, which is in the /home/courses/cs111/handouts/lab11 You can also compare your solution to mine.

Adding __cmp__ method to Person class (10 pts)

Compare two Person objects by their network attribute. The goal is to sort the Person objects by their network attribute, i.e., everyone in the VMI network will come before everyone in the W&L network. Recall the method header for __cmp__ looks like this:

def __cmp__(self, other):
    """ Compares Person objects by their networks (lowercased).
    returns 1 if this one (self) is bigger than the other one.
    returns -1 if this one (self) is smaller than the other one.
    returns 0 if the two are equal. """

    # include the following code to handle when comparing with None
    if type(other) == type(None):
        return -1

As always, test your method. (How can you test the method?)

Adding Searching to your SocialNetwork class (25 pts)

As discussed in class, you will update your SocialNetwork class to include a method that finds all the people that belong to some network. The method will take as parameters the network name to search for and returns a list of people in that network. Your method should:

Your driver program will be responsible for printing out the people that belong to the network or printing out a message if no people match.

There are new Hollywood-related data files in /home/courses/cs111/handouts/lab11/data-files

Adding Exception Handling to your SocialNetwork class (15 pts)

Whenever you open a file for reading or writing in your SocialNetwork class (specifically, in the methods that you implemented: exporting the people file, reading the people file, and reading a connections file), add an appropriate try/except statement to handle file errors. Instead of exiting the program, the exception handler should print a helpful message and return from the method.

A better way: to handle exceptions is for the methods to return True iff the reading or writing of a file is successful. The UI would then check what the method returned and display an appropriate message.

Example output:

Which option do you want? p

What is the name of the file of people you want to add? s
*** Error reading file, s ***
[Errno 2] No such file or directory: 's'

Adding Options to your FaceSpace User Interface Program (15 pts)

Add an option that allows the user to find all the people that belong to some network. This shouldn't be too difficult if you've organized your code well.

Example Run:

ID     Name                      Network         Num Friends
------------------------------------------------------------
1      John Doe                  W & L           3         
2      Jane Smith                W & L           2         
3      James Jones               W & L           2         
4      Henry VIII                Royalty         2         
5      Lady MacBeth              Scotland        1

Select one of the following options:
        (D)isplay the social network
        (V)iew a person in the social network
        Add (P)eople to the social network from a file
        Add (C)onnections to the social network from a file
        Add a (U)ser to the social network
        Add a pair of (F)riends to the social network
        E(X)port the social network
        (S)earch for people in a network
        (Q)uit the program

Which option do you want? s
What network do you want to find that people belong to? scotLAND
1 belong to scotLAND
5: Lady MacBeth in Scotland has 1 friends

...

Which option do you want? s

What network do you want to find that people belong to? W & L
3 belong to W & L
1: John Doe in W & L has 3 friends
3: James Jones in W & L has 2 friends
2: Jane Smith in W & L has 2 friends

...

Which option do you want? s

What network do you want to find that people belong to? scot
No people belong to scot

Demonstrate Your Program

Demonstrate that your program works in IDLE and save that in an appropriately named ".out" file. Show at least one example of attempting to read a file that doesn't exist.

Linux: How Much Code Did You Add?

Run the wc command again. This time, view the size of the .py files in your lab11 directory. Add the output from this command to your mywc.txt file using the >> operator. An example of running wc from your lab11 directory is
wc -l *.py >> mywc.txt

Now, when you view your mywc.txt file, you should be able to compute how many more lines of code you added to your files for this part of the project. Document this difference in comments in your driver program.

Working with 2D Lists

For each of the following problems, create a new Python script.

After you've developed a correct solution to each program, restart IDLE or close and reopen the IDLE "shell" by running the program again (using F5), demonstrate that the program works using several good test cases, and save the output to a file named lab11.x.out, where x is the problem number.

  1. (10 pts) Create a 2D list that looks like:
    [ [0,1,2], [1,3,5], [2,5,8] ]
    

    Simply print the list; do not worry about formatting yet.

    To make each row, you can either use the range function or append to a list, but do not create the list by typing twod=[ [0,1,2], [1,3,5], [2,5,8] ]

  2. (10 pts) Copy the previous program for this program. Add a function that takes a 2D list as a parameter and prints that list so that it looks like the below format. Test on the list you created in the last program.
    0 1 2
    1 3 5
    2 5 8
    
  3. (10 pts) Copy the files connectfour.py, csplot.py, and games.py from /home/courses/cs111/handouts/lab11.
    1. Open up games.py and look at the ConnectFour class. Familiarize yourself with its attributes and how other methods we discussed are implemented.
    2. Run the current implementation from the command-line, using python connectfour.py
    3. Uncomment the makeMove method and its comment and implement the method. Adhere to the method's comment description when implementing the method.
    4. Uncomment the code in the play method, as described in the code. Run and test your game.

      You should only have to modify games.py and none of the other files.

    You won't submit any output from this program.

Extra Credit: ConnectFour

In groups of one to three people, implement the _isDraw (up to 5 pts) and/or _isWon methods (up to 10 pts) of the ConnectFour class. You can receive partial credit.

Alternatively, you can simulate a player so that you make it a one-player game with the computer as the other user. Write a method called makeBestMove that chooses the "best" column to place the checker (up to 10 pts). A naive first approach is to randomly pick a column. A more sophisticated approach is to assign a score to each column that says how "good" a column is for you and select the column with the highest score. What properties would make the column's score increase?

If you work in a group, indicate all group members in comments in the code.

Finishing up: What to turn in for this lab

  1. IDLE and jEdit may create backup files with the "~" extension. Delete these files from your lab directory to save paper when you print.
  2. Copy your lab11 directory into the turnin directory. (Review the UNIX handout if you don't remember how to do that.)
  3. Remove the .pyc files from your directory.
  4. Move csplot.py and connectfour.py into the parent directory. (These are large files that you don't want to print out.)
  5. Use the printLab.sh command to create a file to print out. You should probably print from the labs directory. You may get a warning about the directory containing subdirectories. As long as you don't get an enscript error about unknown special escape, you should be okay.
  6. You can always view the output before you print it, using the gv command, such as
    gv lab11.ps

    Print the file using the lpr command introduced in the first lab.

Labs are due at the beginning of Friday's class. You should hand in the printed copy at the beginning of class, and the electronic version should be in the turnin directory before 1:20 p.m. on Friday.

Ask well before the deadline if you need help turning in your assignment!

Grading (100 pts)