Program 0

Computing Infrastructure

ICS-33: Intermediate Programming


Introduction This first "programming" assignment is not a "programming" assignment at all; it is designed to ensure that you know the fundamentals of using the computing infrastructure for this course, both on your own machine (if you have one) and the computers in our labs. Primarily it concerns starting to learn to use the Eclipse Integrated Development Environment (IDE) for Python programming.

To do this assignment, you must have already downloaded and installed Java, Python, and the Eclipse IDE on your own computer (or be using one of the UCI Lab machines, where it has already been downloaded/installed). Follow the Download/Installation Instructions for your machine, if you need to. Ensure that you have correctly setup the courselib folder and populated it with the required Python modules: otherwise some of your import statements (in parts B, C, and D) will produce errors.

Carefully read and follow the instructions below. It would be an excellent idea to print a copy of this web page, read through it, and highlight any details that you think are important (and might forget as you are working on the assignment) or that you are confused about. Some students lose points for failing to follow directions properly; this is a problem that gets worse during the quarter, so starting out by doing the "right thing" in this assignment is an excellent idea. If you have any questions about these instructions, for example, if you think they are in error, or just confusing, please post on the appropriate MessageBoard Forum; and make sure you examine the posts from other students.

IMPORTANT: Ensure that your Checkmate submission is for the current/correct Quarter, not the previous one.

Finally, carefully read the last two sections, on Extra Credit and Time Management at the end of this assignment. These important sections are relevant to all programming assignments, but appear only in this one.


Part A:
Create a New Project
and Script
Read the Python Programming in the Eclipse IDE web page (which is also accessible on the Handouts web page). It includes all the information that you initially need to know about using Python in the Eclipse IDE. This includes
  • Starting/Stopping Eclipse
  • Running the Python Interpreter
  • Creating Projects in the Eclipse Workbench: new ones and existing ones
  • Editing scripts
  • Correcting syntax errors
  • Running scripts
  • Correcting execution errors
Work through that document to understand Eclipse and gain some experience using it before starting to work on this assignment. Ask your TAs/Lab Tutors questions; please cross the "question answering threshold" quickly; get into the habit of being able to ask ICS-33 staff members questions, especially in lab.

In Part A you will run the Python interpreter to compute an answer, create a new project in the Eclipse workbench, create a new (trivial) script (using the answer computed by the interpreter) without syntax errors, run it to ensure that it executes correctly, and finally submit the script on the Checkmate Homework Dropoff system. Here is a checklist of things to do. If you are confused or run into problems with any one, ask for help as soon as possible.

  • Start Eclipse.
  • Start the Python interpreter in the Console view.
  • Type the following expression into the interpreter; avoid the temptation to cut and paste this expression.
    '{0:,}'.format(2**100)
  • Create a new Python project in the workbench (and thus the workspace) named project0a.
  • Create a new module in this project named demo: the module and file will actually be named demo.py; Eclipse automatically adds the .py.
  • Delete the comment Eclipse puts at the top of your module and replace it by your UCInetID and name in exactly the exact form below (last name before first name), including the correct case (lower and upper), punctuation, spaces, parentheses, and text: e.g.,
    # Submitter: antpeter(Anteater, Peter)
  • After leaving a blank line, type the following Python script into the module: practice with the editor; avoid the temptation to cut and paste this code. Actually, for the big number in single-quotes, it is OK to copy/paste the value that you computed in the interpreter; put it after the comma but before the closing parenthesis.
    print('My first program: a hybrid')
    print('Answer (from Inteprxter) =', '1,267,650,600,228,229,401,496,703,205,376')
  • Fix any syntax errors that Eclipse shows (you might have introduced one by not entering the script correctly). A syntax error is an error, which if not fixed, will stop the programming from executing: it will raise an exception.
  • Run this script to ensure that it produces the correct output in the Console view (once it is executing).
  • Finish the project by closing it in the Eclipse workbench, but do not delete it.

  • Find the Checkmate Homework Dropoff link in the index of the course web and submit your work (the demo.py file in the project0a folder in the workspace for Eclipse) for grading via Checkmate. If you need to, review the Checkmate Tutorial (which is also accessible on the Handouts web page).

  • Reopen the project and ensure that you can still (re)run it.
  • Finish the project by deleting it and delete all its resources; it is now no longer in the workbench or workspace.
  • Redo all these instructions, until you can do them quickly and easily; it would even be useful to practice removing this submission and resubmitting it, so you practice doing that in Checkmate.
  • Terminate Eclipse.
This part of the programming assignment is very cookbook, but by the end you should have mastered the steps needed in creating and manipulating project folders and script files with Eclipse and Checkmate -something you will do over and over again during the quarter.

Part B:
Debug an Old Project's
Script
In Part B you will download and unzip a project and put it into the Eclipse workspace, create a project for it in the Eclipse workbench, correct the syntax errors in the script, run it, correct the execution errors in the script, and finally submit the script on the Checkmate Homework Dropoff sytem. Before beginning this part of the programming assignment, read the short handout on Bugs. Here is a checklist of things to do. If you are confused or run into problems with any one, ask for help as soon as possible.
  • Start Eclipse (terminate it first, if it is currently running); notice the Workspace folder name in the Workspace Launcher pop-up window before you click its OK button.

  • Download the project0b project folder, unzip it to a folder on your desktop. It should contain one module, a file named collatz.py. Move this folder into the workspace.

  • Create a new Python project in the workbench named project0b (using the project0b folder just downloaded and moved into the workspace).
  • Disclose this project in the PyDev Package Explorer view and double click the collatz.py module so that it is visible in an Editor view.
  • Notice the two syntax errors marked in red on line 68 and 76.
    1. If the line numbers do not appear in the Editor view, turn them on.
    2. If there are syntax errors on lines 55 or 56, you have not set up the course library correctly. Read the Course Library installation instructions before proceding.
    Fix the errors as specified below.
  • Fix the syntax error on line 68 by placing a comma right after the token cycle_count and before the token ': test number is now'. If the red syntax error on this line doesn't quickly disappear, issue the right-click | Save command.
  • Notice that a new syntax error appears on line 71; it sometimes happens that one syntax error (line 71) is masked by another (line 68); when we fix one line, a new one shows an error.
  • Hover over the red syntax error icon on line 71 (or the red-underlined token test_number. It says Expected:: which really is Expected: followed by : (the colon it expects).
  • Fix the syntax error on line 71 by placing an equal sign right after the equal sign on this line (no separating spaces): here we must have the == token. If the red syntax error on this line doesn't quickly disappear, issue the right-click | Save command.
  • Hover over the red syntax error icon on line 76 (or the red-underlined token test_numer. It says Undefined variable: test_numer, because we misspelled this name (forgetting the letter b).
  • Fix the syntax error on line 76 by adding a b in the name: it is now spelled correctly as test_number If the red syntax error on this line doesn't quickly disappear, issue the right-click | Save command.

  • Now the script has no syntax errors, so we can run it. Enter 3 to the first prompt and just press enter for the second. It will use the default value of True: with my prompt module, pressing enter is just like typing the default value that appears in square brackets.
  • Python will report show the script starting to run in the Console view and then report an execution error.
    Enter a positive number: 3
    Display intermediate results[True]:
    Cycle 1 : test number is now 3
    Traceback (most recent call last):
      File "C:\Users\Pattis\workspace\project0b\collatz.py", line 75, in 
        cycle_count += '2'
    TypeError: unsupported operand type(s) for +=: 'int' and 'str'
    It identifies an error on line 75, then shows the line, then reports the error, which relates to the fact that the += operator cannot be applied to an integer and a string.
  • Click the underlined line in the console: File "C:\Users\Pattis\workspace\project0b\collatz.py", line 75, in <module>. Python will position your cursor to line 75 in the Editor view. Fix the error there by changing the string literal '2' into the integer literal 2; now the += operator is adding two integers.

  • Run the script, and again enter 3 to the first prompt and just press enter for the second.
  • This time the script runs to completion, but it has an intent error. Notice that the cycle counts increment by two, not one; so our answer says it requires 15 cycles, but it only requires 8.
  • Fix this error in line 75 by changing the integer literal 2 into the integer literal 1.

  • Run the script, and again enter 3 to the first prompt and just press enter for the second. This time the script runs to completion with the correct answer.
  • Finish the project by closing it in the Eclipse workbench, but do not delete it.
  • Find the Checkmate Homework Dropoff link in the index of the course web and use it to submit the collatz.py file in the project0b folder in the workspace for Eclipse.
  • Terminate Eclipse
Again, this part of the programming assignment is very cookbook, but by the end you should have mastered the steps needed in creating and manipulating project folders and script files with Eclipse and Checkmate -something you will do over and over again during the quarter.

Bottom Line

You will be writing many programming assignments during the quarter, requiring you to create new projects or modify existing ones. You should be able to manipulate both kinds of projects easily in Eclipse, and submit them for grading in Checkmate.

Finally, whenever you want to check on a feature in Python or a library module, you should have a very low threshold for quickly starting Eclipse and using its Python Interpeter, or writing a small script, to experiment. It is imperative that you get comfortable with this process immediately.


Part C:
Using the Debug Perspective
In Part C you will read the document that is a tutorial about the Eclipse Debug Perspective and use the debugger to answer a series of seven questions about a program that plays the dice game craps. So, you are not using the debugger to fix a incorrect program, but instead are using it to monitor a correct program and get information about when certain events happen in the program. The debugger is a program that controls your program.

  • Read pages 1-10 and then practice using the debugger by solving all the problems at the bottom of page 10. The solutions are given on page 11...but answer each question before you check its solution, otherwise you will not have exercised your debugging muscles in preparation for solving the problems in the craps program

  • Carefully follow the instructions on page 12 and then solve the problems there: ensure that you change line blank 61 to call dice.standard_rolls_for_debugging(...) with the argument specified there. Solve each more than once: if you aren't getting the same answers every time, you did not correctly follow the instructions on how to setup the craps.py script; re-read those instructions.

  • Download the debugger.zip zip file; unzip it into the debugger.txt text file; write your answers in this text file. IMPORTANT: Use the Eclipse editor to create/modify data files too, like the debugger.txt file. This is especially true if you are on a Mac. Do not use a Mac editor for data files.

  • Find the Checkmate Homework Dropoff link in the index of the course web and use it to submit the debugger.txt file.

Part D:
Test a Module/Class
In Part D you will learn various ways to test Python code with the driver.py module (which is in the courslib), concentrating on how to write a testing file for use with this module's batch_self_check function. You will write such a file to test various factorial functions, and finally submit this file on the Checkmate Homework Dropoff sytem. Here is a checklist of things to do. If you are confused or run into problems with any one, ask for help as soon as possible.
  • Start Eclipse (terminate it first, if it is currently running); notice the Workspace folder name in the Workspace Launcher pop-up window before you click its OK button.

  • Download the project0d project folder, unzip it to a folder on your desktop (it should contain one file named facts.py), and move this folder into the workspace.

  • Create a new Python project in the workbench named project0d (using the project0d folder just downloaded and moved into the workspace).
  • Disclose this project in the PyDev Package Explorer view and double click the facts.py module so that it is visible in an Editor view.
  • Run this script and enter the information below to verify its behavior on these inputs. Basically when driver.driver() is executed, we are simulating a simplified "interpreter" that prompts for and executes the commands that we type (shown below in italics; they appear green in the Console view). In this interaction we first import the fact2 function and then call it with different arguments, printing each result (although some calls raise exceptions).

    We can enter a command at the prompt Command[default]: or just press return in which case default is the command; the default is always the command typed previously. We will discuss the ! and ? commands a bit later.

    Driver started
    Command[!]: from facts import fact2
    
    Command[from facts import fact2]: print(fact2(0))
    1
    
    Command[print(fact2(0))]: print(fact2(5))
    120
    
    Command[print(fact2(5))]:
    120
    
    Command[print(fact2(5))]: print(fact2(-1))
    Traceback (most recent call last):
      File "C:\Users\Pattis\workspace\courselib\driver.py", line 234, in driver
        exec(old,local,globl)
      File "", line 1, in 
      File "C:\Users\Pattis\workspace\project0d\facts.py", line 11, in fact2
        raise ValueError('factorial('+str(n)+') not defined for negative values')
    ValueError: factorial(-1) not defined for negative values
    
    Command[print(fact2(-1))]: print(fact2('a'))
    Traceback (most recent call last):
      File "C:\Users\Pattis\workspace\courselib\driver.py", line 234, in driver
        exec(old,local,globl)
      File "", line 1, in 
      File "C:\Users\Pattis\workspace\project0d\facts.py", line 9, in fact2
        raise TypeError('factorial('+str(n)+') must be called with an int argument')
    TypeError: factorial(a) must be called with an int argument
    
    Command[print(fact2('a'))]: quit
    Driver stopped
The most interesting aspect of the driver module is its batch_self_check function, which automatically reads, decodes, and executes testing commands from a file (specified by the first two arguments), summarizing the results (how each result is printed is based on the final arguments to the function). Each parameter has a default argument, and all of them are set at the top of the driver.py module. You can explore different argument values, but the default values are the most useful.

We can call this function explicitly in the "interpreter", supplying it with the necessary arguments, but mostly we call it via the ! command (calling it with all default arguments) or the ? command (calling it with arguments entered by prompts to the user). The following paragraphs briefly describe how to write commands in a testing file; then you will be asked to write a testing file for the functions in the facts.py module.

A testing file is a sequence of lines, each of which contains one testing command. The character(s) starting each testing command determines what is tested. Lines starting with # are special; they are comment lines; all other (non-blank) lines should start with a c, e, ^, or relational operator (==, !=, <, <=, >, >=, in, or not in). Each c command is followed by one operand; each e, ^, or relational operator is followed by two operands (which are each prefaced by a special separator string: the default separator value is -->).

  • Command: c-->operand
    Execute operand as a Python statement; it is an Error if the statement raises any exception. An example might be c-->from math import factorial or c-->x = [1,2,3,4,5].

  • Evaluate: e-->operand1-->operand2
    Evaluates operand1 as a Python expression, converts it to a string, and determines whether or not it is the same string as operand2; it is an Error if the strings are not equal or evaluating operand1 raises an exception (operand2 must be present, and its characters are treated as a string, therefore it is not evaluated). An example might be e-->factorial(5)-->120, which would not be an Error; but e-->factorial(2,5)-->120 and e-->factorial(5)-->110 would both be Errors: the first raises a TypeError exception (because the function define only one parameter although this calls supplies two) and the second compares '120' != '110', which are not equal.

  • Exception: ^-->operand1-->operand2
    Executes operand1 as a Python statement and determines whether or not an exception is raised matching operand2 (either a single exception name, a list of exception names separated by commas, or * which means any exception name); there is an Error if no exception is raised or an exception not named by operand2 is raised. An example might be ^-->factorial(-1)-->ValueError, which would not be an Error; but ^-->factorial(2)-->* and ^-->factorial(-1)-->TypeError,ZeroDivisionError would both be Errors: the first raises no exception and the second raises a ValueError exception, which is neither TypeError nor ZeroDivisionError.

  • Relational Operator: relop-->operand1-->operand2
    Evaluates operand1 and operand2 as Python expressions, and determines whether the relop holds between them; it is an Error if relop does not hold or evaluating either operand raises an exception. An example might be ==-->2*3-->3*2, which would not be an Error; but in-->'a'-->['b','c','d'] would be an Error: the character 'a' is not in the list ['b','c','d'].

    Can you explain why e-->2*3-->3*2 would be an Error? Can you explain why in-->a-->['a','b','c'] would be an Error?

  • Comment: #any text
    Prints the line number and #any text on the console. Nothing is tested. So lines that begin with # are treated like comments.
Given these formats write a test file and run the batch_self_check function (with the standard default arguments) on it.

IMPORTANT: Use the Eclipse editor to create/modify data files too, like the bsc.txt file. This is especially true if you are on a Mac. Do not use a Mac editor for data files.

  • Write a test file named bsc.txt (the default file name) that does the following (each requirement translates into one line in the file, so the file should contain 22 lines total). I suggest that you incrementally write and test this file: it requires running the facts.py module only once: each time you update the bsc.txt file with another test, just reissue the ! command (the original default) in the Console view, without stopping/rerunning the driver function.
    1. Imports the factorial function from the math module.
    2. Imports the fact1 and fact2 functions from the facts module.
    3. Comments that fact1 is now being tested.
    4. Checks whether the call fact1('a') raises the TypeError exception (it doesn't).
    5. Checks whether the call fact1(-1) raises the ValueError exception (it doesn't).
    6. Checks whether the call fact1(0) returns the value 1 (it doesn't).
    7. Checks whether the call fact1(5) returns the value 120 (it doesn't).
    8. Checks whether the call fact1(10) returns the same value as factorial(10) (it doesn't).
    9. Checks whether the call fact1(10) returns the same value as 10*9*8*7*6*5*4*3*2*1 (it doesn't).
    10. Checks whether the call fact1(100) returns the same value as 100*fact1(99) (it does, because both are 0).
    11. Comments that fact2 is now being tested.
    12. Checks whether the call fact2('a') raises the TypeError exception (it does).
    13. Checks whether the call fact2(-1) raises the ValueError exception (it does).
    14. Checks whether the call fact2(0) returns the value 1 (it does).
    15. Checks whether the call fact2(5) returns the value 120 (it does).
    16. Checks whether the call fact2(10) returns the same value as factorial(10) (it does).
    17. Checks whether the call fact2(10) returns the same value as 10*9*8*7*6*5*4*3*2*1 (it does).
    18. Checks whether the call fact2(100) returns the same value as 100*fact2(99) (it does).
    19. Comments that sets are now being tested.
    20. Binds name x to a set containing an 'a', 'b', 'c', and 'd'.
    21. Removes the value 'b' from set x.
    22. Checks whether set x is the same as a set containing an 'a', 'c', and 'd'.

  • Run the facts.py script, using the ! command to perform all the batch self tests specified in the file you constructed above, and verify it is producing the correct results when testing these functions.

    When I ran my bsc.txt file with these 22 lines, the results look as follows (except I had to elide some lines that the driver prints, because it would show the exact lines that need to be entered in the file, so the lines containing ..... are elided):

    Starting batch_self_check
        3 # Testing fact1
        4 ....
          *Error: ^--> failed to raise any exception
        5 ....
          *Error: ^--> failed to raise any exception
        6 ....
          *Error: e--> failed
             left  value: '0'
             right value: '1'
        7 ....
          *Error: e--> failed
             left  value: '0'
             right value: '120'
        8 ....
          *Error: == operator failed to evaluate to True
             left  value: 0
             right value: 3628800
        9 ....
          *Error: == operator failed to evaluate to True
             left  value: 0
             right value: 3628800
       11 # Testing fact2
       19 # Testing sets
    Done batch_self_check: 9 correct; 6 incorrect
    Failed checks: [4, 5, 6, 7, 8, 9]
    Note that of the 22 lines, 3 are comments (starting with #), 15 are tests (starting with e-->, ^-->, or ==-->), and 4 are "setup" (starting with c-->).
  • Find the Checkmate Homework Dropoff link in the index of the course web and use it to submit the bsc.txt file in the project0d folder in the workspace for Eclipse. If you need to, review the Checkmate Tutorial (which is also accessible on the Handouts web page).
Generally feel free to examine how the entire driver.py module (and especially the batch_self_test function) works, by reading its code.

Extra Credit Programming assignments must be turned in on time: you can get partial credit for a partially completed assignment, but it must be turned in on time; I will accept no late homework unless you have an official excuse pre-arranged with me (and even then I will always want you to turn in whatever work you have completed by the due date/time). In fact, there is another incentive to finish not only on time, but to finish early.

In all programming assignments, if you turn in everything at least 24 hours before it is officialy due, you will receive 1 point of extra credit. If you turn it in 48 hours (or earlier), you will receive 2 points of extra credit. (There is no more extra credit for early turn-ins; I recommend NOT turning it in more than 48 hours early.) This is equivalent to almost half a grade improvement (e.g., C+ to B, or B to B+, or B+ to A-) on a 50 point assignment. I expect most of the students to complete their assignments and submit them early, so they will receive some amount of extra credit; it adds up.

There are two main advantages to planning on finishing early. First, if you run into a major problem, you will have extra time to solve it before the actual due date: and even experienced programmers frequently run into such problems. Yes, this means you! Second, and more importantly, if you are racing to finish before a deadline, stress levels can go through the roof, and you become less interested in learning the material (and the whole purpose of these programming assignments is to learn the material) and more interested in just getting finished before the deadline. If you do not learn the material, then you will be at a major disadvantage for subsequent programming assignments and tests, because of the cumulative nature of the material in this course. Therefore, work on an aggressive schedule and plan to finish every assignment by Sunday or Monday evening (or even earlier).

Programming assignments sometimes also include an extra credit section worth 1 point. These are designed for students who finish early and want to continue exploring programming within the context of the assignment. The single point is to acknowledge, in a very small way, their extra effort.

This assignment has no special extra-credit section. You can get extra credit on it only for an early dropoff.


Time Management One of the hardest parts of being in college is learning how to manage your time. Time management is especially important in programming courses (and in the real world, when you are working on complicated projects with hard deadlines). The difference between good and bad time management can have a profound impact on how much you learn in this course, how well you perform in it, how much effort you actually need to expend to do well, and how you feel about the course..

Most programming assignments can be broken into a series of smaller tasks, each that can serve as a milestone; when solved in sequence, these tasks will complete the entire assignment.

Generally, it is best to spread out the work on a two-week assignment. Most assignmnts become available on Tuesday morning; I recommend reading the assignment before/during lab, so that if you are unsure about any parts of it, you can ask relevant questions about them on the Forum; this reading might include examining and understanding code provided in the writeup. You should start working on it during lab, and should plan to complete at least half the programming assignment by the next Tuesday lab. You should try to finish it by late the following the week: if not by Friday, you can work over the weekend to finish it. In a worst-case scenario you can use the lab on Tuesday to finish, asking final questions of the staff during that lab.

Some students look at an assignment and think that it is best done in one sitting. If you can do so, great; but, if you plan to work this way, do the one sitting early, not the weekend before it is due. In this way, if you are wrong about the amount of time that it will take, you will still have adequate time to complete the assignment.

Likewise, I have seen students who always spend Tuesday finishing the previous assignment, and not get around to looking at and starting the next one. This starts them on a bad path for finishing the next assignment.

By meeting these time goals, you will both maximize what you learn and minimize your anxiety and the time that it takes for you to do the learning.

Remember that assignments must be turned in on time: you can get partial credit for a partially completed assignment, but it must be turned in on time; I will accept no late homework unless you have an official excuse pre-arranged with me (and even then I will always want you to turn in whatever work you have completed by the due date/time).

Finally, if you find yourself falling behind, seek help immediately (from me, the TA, the Lab Tutor, or even other students in the course - but only in ways that preserve academic integrity). When the real programs start, we will discuss in more detail what kind of help you can get legitimately, and what kind of help constitutes academic misconduct (cheating).