Skip to main content.

Lab 11: Binary Search and 2D Lists

Goals

After the lab, you should be proficient at

  1. adapting "basic" binary search for use in another algorithm
  2. creating and processing 2D lists

Review

Review the slides for today.

Objective: Set up

  1. Copy the entire directory /csdept/courses/cs111/handouts/lab11 into your cs111 directory.
  2. Copy the files (although not the entire directory) from your lab10 directory into the lab11 directory so that you can extend your FaceSpace application in this lab.

Objective: How Big Is My Program? (10 pts)

You've been writing code for 11 weeks (or so), and the programs have gotten larger. Last week's lab was the largest yet. In the grand scheme of programming, this code is still relatively small, but it's not small to you!

(This is not ideal, in that you may not be looking at your own code. I recommend that you do this on your own in your directory, although you will not submit that.)

Objective: Programming in Python

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 /csdept/courses/cs111/handouts/lab10_solution/ You can also compare your solution to mine.

Adding Search Functionality to FaceSpace (48 pts)

As discussed in class, you will update your FaceSpace to find a person with a certain name. For improved usability, it shouldn't matter if the user capitalizes the name appropriately. We also need to make a few changes to the original binary search function so that it can be turned into a method of the SocialNetwork class.

As before, for each of the classes, you should save an output file with the tests you ran.

Add __lt__(self, other) method to Person class (12)

If we implement the __lt__ method, we can compare two Person objects using <. If __lt__ is implemented, then list's sort method will use __lt__ to order the objects, by default.

    def __lt__(self, other):
        """Takes as a parameter a Person object named other.
        Returns True if this person's name, lowercased, comes before
        the other person's name, lowercased, alphabetically.
        Otherwise, returns False.
        """

Implement the above method in the Person class.

  1. Test the method by comparing two Person objects, for example:
      print(person1 < person2)
      print(person2 < person1)
      test.testEqual(person1 < person2, True)
      test.testEqual(person2 < person1, False)
    

    The above print statements should print either True or False.

    Consider what are good test cases for the given functionality.

  2. Then, create a list of Person objects and make sure that sorting the list of Person objects does what is expected.

Searching for a Person with the given name (26)

Add a search method to the SocialNetwork class. The method will take as a parameter the name to search for and returns a person who has that name.

    def searchForPerson(self, name):
        """Search for the person with the given name (a string) in the social network.
        Returns a Person with this name, ignoring case, or None if no person with this
        name exists in the social network.
        """

Note, unlike the function we wrote in class, the method does not take as a parameter the list of Person objects. Where should that list of Person objects come from?

Your method should leverage binary search to find a person that has the given name. Recall: What does binary search require of the list it searches?

For better usability, the search shouldn't care whether the name is capitalized correctly. Therefore, you should lowercase the given name to search for to get the most intuitive results. (Save the result in a variable so you don't have to keep performing these operations on the name.)
If the given key is lowercased, what should you do to the Person's name?

What are good test cases for this method?

Your user interface will be responsible for printing out the person with that name or printing out a message if no one matches.

We've been programming for 11 weeks now. Do what you can to help you visualize what is happening--draw pictures, print out variables. Use small datasets instead of trying to work on a large set. Name variables by their data types so you remember what you're working with. Review/execute related examples to make sure you understand what they did.

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

Add an option that allows the user to search for a person with a given name.

Example Run:

ID     Name                      Num Friends
---------------------------------------------
1      John Doe                            3         
2      Jane Smith                          2         
3      James Jones                         2         
4      Henry VIII                          2         
5      Lady MacBeth                        1
6      John Doe                            2

Select one of the following options:
        (D)isplay the social network
        (V)iew a person in the social network
        (S)earch for people 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
        (Q)uit the program

Which option do you want? s
What is the name of the person you want to find? jane SMITH

Jane Smith (id: 2) has 2 friends


Which option do you want? s

What is the name of the person you want to find? Lady
No person named Lady found.

Demonstrate FaceSpace

Demonstrate that your program works in IDLE (just the new functionality: searching) and save the output in an appropriately named ".out" file.

You must demonstrate the search functionality on a larger data set. How can you add more people to your social network easliy?

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 lines of code in comments in social.py.

Working with 2D Lists (42)

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. (12 pts) Create a 2D list that looks like:
    [ [0,1,2], [1,3,5], [2,5,8] ]
    

    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] ]

    Simply print the list, as a list; do not worry about formatting yet. (See the next problem.)

  2. (15 pts) Copy the previous program for this program. Add a function that takes a two-dimensional 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, as well as several other lists, all in one execution of the program.
    0 1 2
    1 3 5
    2 5 8
    
  3. (15 pts)
    1. Open up connectfour.py that you copied earlier and look at the ConnectFour class.

      Familiarize yourself with its attributes and how other methods are implemented. Investing your time in understanding the existing code will result in faster implementation of the solution. What is the data for this class? How do the (fully implemented) methods manipulate this data?

    2. Uncomment the makeMove method and its docstring comment and implement the method. Make sure the indentation is correct. Adhere to the method's comment description when implementing the method.
    3. Uncomment the code in the play method, as described in the code. Run connectfour.py to test your game.
    4. You should only have to modify connectfour.py--not csplot.py.

    You have to hit Control-C in the terminal to kill the game. Attempting to close the window does not work.

    You won't submit any output from this program.

Extra Credit: Searching (up to 8 points)

The search functionality is pretty limited -- it only finds one person with the matching name.

Modify the binary search to find all the people with a certain name. If you search for "Jane Smith", there is probably more than one person with that name. Modify your search so that it returns a list of Person objects, rather than just one of the possible people. Where will the other people with that same name be with respect to the person you found using binary search?

Extra Credit: ConnectFour

Implement the _isDraw (up to 5 pts) or_isWon methods (up to 10 pts) of the ConnectFour class. You can receive partial credit.

Alternatively, you can improve the _computerMakeMove method that chooses the "best" column to place the checker (up to 10 pts). A naive first approach (which is currently implemented) 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?

Finishing up: What to turn in for this lab

  1. When you, as a pair, are ready to submit OR if you are at the end of the lab period, run pairturnin.sh labx partnerusername
    where labx is the name of the lab you are submitting and partnerusername is your partner's username on the lab machines (the person whose account you are not using to write the code). For more information about the command, see the wiki.

    If you want to copy your pairs' work into your cs111 directory--either just to have it or to work on your code on your own--use the script startup.sh. Run this command from the account that you want For example, run startup.sh labx partnerusername
    where labx is the name of the lab you're working on and partnerusername is your partner's username on the lab machines.

    For more info, see the wiki.

  2. If you complete the lab on your own after the lab period, submit your lab into your turnin directory.
  3. IDLE and jEdit may create backup files with the "~" extension. Delete these files from your lab directory to save paper when you print.
  4. Move csplot.py into the parent directory. (This is a large file that you don't want to print out.)
  5. Remove any .pyc files from the directory (e.g., created if you accidentally ran using Python 2); otherwise, you'll get an error when creating the output file.
  6. Perform the following steps from your cs111 directory.

    Note that each command below links to a page with more information about using the command.

  7. Create the printable lab assignment, using the createPrintableLab command:
    createPrintableLab <labdirname>
  8. View your file using the evince command.
  9. Print the file using the lpr command.
  10. Log out of your machine when you are done.

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 class on Friday.

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

Grading (100 pts)