2016 Lab 0

From 6.034 Wiki

Revision as of 23:35, 29 August 2016 by Jmn (Talk | contribs)
Jump to: navigation, search


Note: As with all labs, you will need to have a key file in order to submit.


Contents

The purpose of this lab is to familiarize you with this term's lab system and to diagnose your programming ability and facility with Python. 6.034 uses Python for all of its labs, and you will be called on to understand the functioning of large systems, as well as to write significant pieces of code yourself.

While coding is not, in itself, a focus of this class, artificial intelligence is a hard subject full of subtleties. As such, it is important that you be able to focus on the problems you are solving, rather than the mechanical code necessary to implement the solution.

If Python doesn't come back to you by the end of this lab, we recommend that you seek extra help through the Course 6/HKN tutoring program, which matches students who want help with students who've taken and done well in a class. The department pays the tutor, and the program comes highly recommended.

Python resources

Some resources to help you knock the rust off of your Python:


Python

There are a number of versions of Python available. 6.034 uses standard Python ("CPython") from http://www.python.org/. If you are running Python on your own computer, you should download and install Python 2.5, Python 2.6, or Python 2.7 from http://www.python.org/download/ . All the lab code will require at least version 2.3. Please note that our code is not designed to work with Python 3.

If you are using Windows: When run on Windows, Python versions 2.6.5 through 2.7.3 seem to be incompatible with our server. The recommended solution is to install a version of Python >= 2.7.4 or <= 2.6.4. For example, Python 2.7.10 works well on Windows.

Mac OS X comes with Python 2.3 pre-installed, but the version you can download from python.org has better support for external libraries and a better version of IDLE.

You can run the Python interpreter on Athena like this:

 add python
 idle &

You can, of course, edit Python files in a plain-text editor, and run them on Athena like this:

 add python
 python filename.py

Getting the lab code

If you are working on Athena
The code for the labs is in the 6.034 locker. You can get lab 0 like this:

 attach 6.034
 mkdir -p ~/6.034-labs/lab0/
 cp -R /mit/6.034/www/labs/lab0/* ~/6.034-labs/lab0/

Then, you can edit the code in your ~/6.034-labs/lab0 directory.
You can ssh into linux.mit.edu to work on Athena from a different computer (thank you SIPB)
If you are working on another computer with Python
Create a folder for the lab.
Download this file and extract it: http://web.mit.edu/6.034/www/labs/lab0/lab0.zip

You can also view the code without downloading it: http://web.mit.edu/6.034/www/labs/lab0/

Getting the Submit Key

In order to submit your labs, you must download a "key.py" file and place it in the same directory as your labs. The "key.py" file contains login information used by the tester to identify you personally to the testing server. You can continue using the same key throughout the semester unless you change your Athena password, in which case you may need to download a new "key.py".

You can download a key from https://ai6034.mit.edu/labs . Make sure that you have an up-to-date MIT Certificate before going to this page. If the page doesn't work in Apple's Safari Web browser (because of a bug in Safari regarding certificates), use Firefox/Chrome instead, or download the file on Athena.

Answering questions

The main file of this lab is called lab0.py. Open that file in IDLE (or your preferred Python editor). The file contains a lot of incomplete statements for you to fill in with your solutions.

The first item to fill in is a multiple choice question. The answer should be extremely easy. Many labs will begin with some simple multiple choice questions to make sure you're on the right track.

Run the tester

Every lab comes with a file called tester.py. This file checks your answers to the lab. For problems that ask you to provide a function, the tester will test your function with several different inputs and see if the output is correct. For multiple choice questions, the tester will tell you if your answer was right. Yes, that means that you never need to submit wrong answers to multiple choice questions.

The tester has two modes: "offline" or "local" mode (the default), and "online" or "submit" mode. The offline tester runs some basic, self-contained internal tests on your code. The online tester runs more tests, some of which may be randomly generated, and uploads your code to the 6.034 grader for grading.

You can run both testers as many times as you want. If your code fails a test, you can submit it and try again. Because you always have the opportunity to fix your bugs, you can only get a 5 (out of 5) on a lab if it passes all the tests. If your code fails a test, your grade will be 4 or below.

Your grade online will never decrease, so you should submit your code online early and often. Think of it as being like the "Check" button from 6.01: It makes sure you're not losing points unnecessarily. Submitting your code also makes it easy for the staff to look at it and help you.

Using IDLE

If you are using IDLE, or if you do not have easy access to a command line (as on Windows), IDLE can run the tester.

Open the tester.py file and run it using Run Module or F5. This will run the offline tests for you. When you want to submit to the online tester, you can run

 test_online()

to submit your code and run the online tests.

In fact, it will run the submission and online test just as soon as it completes offline tests, saving you a few keystrokes.

Using the command line

If you realize just how much emacs and/or the command line rock, then you can open your operating system's Terminal or Command Prompt, and cd to the directory containing the files for Lab 0. Then, run:

python tester.py

to run the offline tester, and

python tester.py submit

to submit your code and run the online tester.

Python programming

Now it's time to write some Python!

(Note: The programming part of Lab 0 is optional; for full credit, you only need to fill in the survey questions and submit your code online. However, we highly recommend completing the programming part, as it will be good practice for future labs!)

Warm-up: Exponentiation

Write a function that takes in a number x and returns its cube. For example, cube(3) -> 27.

def cube(x):

Write a function that takes in a number x and returns its zenzizenzizenzic, which is a fun word for the eighth power of a number.

def zenzizenzizenzic(x):

Hint: Use ** or math.pow() to avoid writing x eight times.

String Manipulation

todo formatting

  1. practice using strings, lists, and sets, and returning a tuple of arguments
  2. Hint: It's possible to write this function without using the keywords "for" or
  3. "while". If you're not sure how, feel free to come to office hours. The
  4. answer key will also demonstrate a number of useful shortcuts.
  1. example: "hello" -> (5, ["o", "l", "l", "h", "e"], 4)

def analyze_string(string):

   """Given a string of lowercase letters, return a tuple containing the
   following three elements:
       0. The length of the string
       1. A list of all the characters in the string (including duplicates, if
          any), sorted in REVERSE alphabetical order
       2. The number of distinct characters in the string (hint: use a set)
   """
   raise NotImplementedError


  1. Given a string consisting of lowercase letters, return a dictionary mapping
  2. each letter to the number of times it occurs in the string
  3. Example: "hello" -> {"h": 1, "e": 1, "l": 2, "o": 1}

def tally_letters(string): #todo make this more like labs? or remove?

   raise NotImplementedError

Recursion

todo formatting

  1. Write a function that returns the nth Fibonacci number (hint: use recursion)
  2. You may assume that n is a positive integer.

def fibonacci(n):

   raise NotImplementedError
We suggest that you should write your functions so that they raise nice clean errors instead of dying messily when the input is invalid. For example, it would be nice if factorial rejected negative inputs right away; otherwise, you might loop forever. You can signal an error like this: raise Exception, "factorial: input must not be negative"
Error handling doesn't affect your lab grade, but on later problems it might save you some angst when you're trying to track down a bug.


  1. Expression Depth (see old wiki)

def expression_depth(expr):

   raise NotImplementedError

Functions that Return Functions

todo formatting

  1. write a function that takes in a multiplier m (a number) and returns a function that multiplies its input by m
  2. That is, after you implement this, you should be able to do
  3. my_multiplier_fn = create_multiplier_function(5)
  4. to define a function my_multiplier_fn that multiplies its input by 5:
  5. my_multiplier_fn(3) -> 15
  6. my_multiplier_fn(-10) -> -50

def create_multiplier_function(m):

   "Given a multiplier m, returns a function that multiplies its input by m."
   raise NotImplementedError

Objects and APIs

todo formatting

  1. make copies of an object and modify them separately

""" Many of our labs include an API for an object class that we defined. The API is a brief description of the attributes and functions in the class that we provide so that you don't need to waste any time reading the source code.

Here's an example:

Point API

A Point object represents a point in the 2-D Cartesian plane. It has X and Y coordinates which you can access or modify:

  • point.getX(): returns current X value
  • point.getY(): returns current Y value
  • point.setX(x): sets the X value to x, then returns the point
  • point.setY(y): sets the Y value to y, then returns the point

Point objects also support the following methods:

  • point.copy(): Returns a copy of the point object

You can use == to check whether two points have the same coordinates. You can also use "print" to print out a human-readable Point object. """

Copying and modifying objects

todo formatting

  1. Given a Point object, return a list containing its four neighboring points in any order (there are multiple correct answers)
  2. (only counting vertical/horizontal neighbors; no diagonal neighbors)
  3. Assume all coordinates are integers.
  4. Do not modify the original point. Do not create new Point objects; instead, make copies of the original point and modify them.
  5. Debugging hint: If your answer looks the same as the expected answer but the
  6. tests aren't passing, make sure you're not creating new Points or modifying
  7. the original! The tester checks for this!

def get_neighbors(point):

   """Given a Point object, returns a list of the point's four neighboring
   points in the horizontal and vertical directions, without modifying the
   original point or using the Point constructor."""
   raise NotImplementedError

Using the "key" argument

todo formatting

note you can also do this with simple objects, eg sorting tuples based on their third element

  1. Given a list of Points, sort them in increasing order based on their Y values.
  2. You may assume that no two points have the same Y value.
  3. Do NOT modify the original list (that is, don't sort in-place).
  4. Hint: use sorted with a key argument

def sort_points_by_Y(list_of_points):

   """Given a list of Points, sorts them in increasing order based on their Y
   values, without modifying the original list."""
   raise NotImplementedError


  1. Given a list of points, return the point that is furthest to the right (largest X value)
  2. You may assume that no two points have the same X values.
  3. Hint: Use max with a key argument. You don't need to sort the list.

def furthest_right_point(list_of_points):

   """Given a list of Points, returns the one that is furthest to the right
   (that is, the one with the largest X value)."""
   raise NotImplementedError

Expression depth

One way to measure the complexity of a mathematical expression is the depth of the expression describing it in Python lists or tuples. Write a program that finds the depth of an expression.

For example:

  • depth('x') => 0
  • depth(('expt', 'x', 2)) => 1
  • depth(['+', ['expt', 'x', 2], ['expt', 'y', 2]]) => 2
  • depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4


Note that you can use the built-in Python "isinstance()" function to determine whether a variable points to a list of some sort. "isinstance()" takes two arguments: the variable to test, and the type (or list of types) to compare it to. For example:

>>> x = [1, 2, 3]
>>> y = "hi!"
>>> isinstance(x, (list, tuple))
True
>>> isinstance(y, (list, tuple))
False

Tree reference

float

Your job is to write a procedure that is analogous to list referencing, but for trees. This "tree_ref" procedure will take a tree and an index, and return the part of the tree (a leaf or a subtree) at that index. For trees, indices will have to be lists of integers. Consider the tree in Figure 1, represented by this Python tuple: (((1, 2), 3), (4, (5, 6)), 7, (8, 9, 10))

To select the element 9 out of it, we’d normally need to do something like tree[3][1]. Instead, we’d prefer to do tree_ref(tree, (3, 1)) (note that we’re using zero-based indexing, as in list-ref, and that the indices come in top-down order; so an index of (3, 1) means you should take the fourth branch of the main tree, and then the second branch of that subtree). As another example, the element 6 could be selected by tree_ref(tree, (1, 1, 1)).

Note that it’s okay for the result to be a subtree, rather than a leaf. So tree_ref(tree, (0,)) should return ((1, 2), 3).

Symbolic algebra

Throughout the semester, you will need to understand, manipulate, and extend complex algorithms implemented in Python. You may also want to write more functions than we provide in the skeleton file for a lab.

In this problem, you will complete a simple computer algebra system that reduces nested expressions made of sums and products into a single sum of products. For example, it turns the expression (2 * (x + 1) * (y + 3)) into ((2 * x * y) + (2 * x * 3) + (2 * 1 * y) + (2 * 1 * 3)). You could choose to simplify further, such as to ((2 * x * y) + (6 * x) + (2 * y) + 6)), but it is not necessary.

This procedure would be one small part of a symbolic math system, such as the integrator presented in Monday's lecture. You may want to keep in mind the principle of reducing a complex problem to a simpler one.

An algebraic expression can be simplified in this way by repeatedly applying the associative law and the distributive law.

Associative law
((a + b) + c) = (a + (b + c)) = (a + b + c)
((a * b) * c) = (a * (b * c)) = (a * b * c)
Distributive law
((a + b) * (c + d)) = ((a * c) + (a * d) + (b * c) + (b * d))

The code for this part of the lab is in algebra.py. It defines an abstract Expression class, Sum and Product expressions, and a method called Expression.simplify(). This method starts by applying the associative law for you, but it will fail to perform the distributive law. For that it delegates to a function called do_multiply that you need to write. Read the documentation in the code for more details.

This exercise is meant to get you familiar with Python and using it to solve an interesting problem. It is intended to be algorithmically straightforward. You should try to reason out the logic that you need for this function on your own. If you're having trouble expressing that logic in Python, though, don't hesitate to ask a TA.

Some hints for solving the problem:

  • How do you use recursion to make sure that your result is thoroughly simplified?
  • In which case should you not recursively call simplify()?

Survey

We are always working to improve the class. Most labs will have at least one survey question at the end to help us with this. Your answers to these questions are purely informational, and will have no impact on your grade (as long as you answer the ones that are required).

Please answer these questions at the bottom of your lab0.py file:

  • PYTHON_EXPERIENCE: How much experience do you have with Python?
A. No experience (never used Python before this semester)
B. Beginner (just started learning, e.g. took 6.0001)
C. Intermediate (have used Python in a couple classes/projects)
D. Proficient (have used Python for multiple years or in many classes/projects)
E. Expert (could teach a class on Python)
  • NAME: What is your name? (string)
  • COLLABORATORS: Other than 6.034 staff, whom did you work with on this lab? (string, or empty string if you worked alone)
  • HOW_MANY_HOURS_THIS_LAB_TOOK: Approximately how many hours did you spend on this lab? (number or string)
  • (optional) SUGGESTIONS: What specific changes would you recommend, if any, to improve this lab for future years? (string)

When you're done

Remember to run the tester! The tester will automatically upload your code to the 6.034 server for grading and collection.

FAQ

It's quite possible that this lab -- or, in particular, the grader system -- will have issues that need to be fixed or things that need to be clarified.

If you have a question or a bug report, send an e-mail to 6.034-2015-support@mit.edu.


Q: When I submit to the online tester, it says I passed all the tests, but it shows my grade as 0.00.

A: Try downloading a new key.py file.


Q: When I submit to the online tester, it hangs for a while and/or eventually prints a stack trace ending in httplib.BadStatusLine: ' '

A: If you're using Windows, review the Python section and make sure you're using a compatible version of Python. If that doesn't solve the problem, contact a TA.

Personal tools