$24.99
Introduction
The projects for this class assume you use Python 3.6.
Project 0 will cover the following:
A mini-UNIX tutorial (particularly important if you work on instructional machines),
Instructions on how to set up the right Python version,
A mini-Python tutorial,
Project grading: Every project’s release includes its autograder for you to run yourself.
Files to Edit and Submit: You will fill in portions of addition.py , buyLotsOfFruit.py , and shopSmart.py in tutorial.zip during the assignment. You should submit these files with your code and
comments. Please do not change the other files in this distribution or submit any of our original files other than these files.
Discussion: Please be careful not to post spoilers.
Unix Basics
Here are basic commands to navigate UNIX and edit files.
File/Directory Manipulation
When you open a terminal window, you’re placed at a command prompt:
Some other useful Unix commands: cp copies a file or files rm removes (deletes) a file mv moves a file (i.e., cut/paste instead of copy/paste) man displays documentation for a command pwd prints your current path xterm opens a new terminal window firefox opens a web browser
Press “Ctrl-c” to kill a running process
Append & to a command to run it in the background fg brings a program running in the background to the foreground
The Emacs text editor
Some basic Emacs editing commands ( C- means “while holding the Ctrl-key”):
C-x C-s Save the current file
C-x C-f Open a file, or create a new file it if doesn’t exist
C-k Cut a line, add it to the clipboard
C-y Paste the contents of the clipboard
C-_ Undo
C-g Abort a half-entered command
You can also copy and paste using just the mouse. Using the left button, select a region of text to copy. Click the middle button to paste.
There are two ways you can use Emacs to develop Python code. The most straightforward way is to use it just as a text editor: create and edit Python files in Emacs; then run Python to test the code somewhere else, like in a terminal window. Alternatively, you can run Python inside Emacs: see the options under “Python” in the menubar, or type C-c ! to start a Python interpreter in a split screen. (Use C-x o to switch between the split screens, or just click if C-x doesn’t work).
If you want to spend some extra setup time becoming a power user, you can try an IDE like Eclipse (Download the Eclipse Classic package at the bottom). Check out PyDev for Python support in Eclipse.
Python Installation
Many of you will not have Python 3.6 already installed on your computers. Conda is an easy way to manage many different environments, each with its own Python versions and dependencies. This allows us to avoid conflicts between our preferred Python version and that of other classes. We’ll walk through how to set up and use a conda environment.
Prerequisite: Anaconda. Many of you will have it installed from classes such as EE 16A; if you don’t, install it through the link.
Creating a Conda Environment
The command for creating a conda environment with Python 3.6 is:
Entering the Environment
To enter the conda environment that we just created, do the following. Note that the Python version within the environment is 3.6, just what we want.
Leaving the Environment
Leaving the environment is just as easy.
Our python version has now returned to whatever the system default is!
Using the Lab Machines
At the moment, students do not have the right permissions to download Python 3.6 or Conda on the lab machines. For P0, Python 3.5 (which is already installed) will suffice.
Python Basics
Required Files
You can download all of the files associated with the Python mini-tutorial as a zip archive: python_basics.zip. If you did the unix tutorial in the previous tab, you’ve already downloaded and unzipped this file.
The programming assignments in this course will be written in Python, an interpreted, object-oriented language that shares some features with both Java and Scheme. This tutorial will walk through the primary syntactic constructions in Python, using short examples.
We encourage you to type all python shown in the tutorial onto your own machine. Make sure it responds the same way.
Invoking the Interpreter
Python can be run in one of two modes. It can either be used interactively, via an interpeter, or it can be called from the command line to execute a script. We will first use the Python interpreter interactively.
You invoke the interpreter using the command python at the Unix command prompt; or if you are using Windows that doesn’t work for you in Git Bash, using python -i .
Operators
The Python interpreter can be used to evaluate expressions, for example simple arithmetic expressions. If you enter such expressions at the prompt ( >>> ) they will be evaluated and the result will be returned on the next
Strings
There are many built-in methods which allow you to manipulate strings.
We can also store expressions into variables.
In Python, you do not have declare variables before you assign to them.
Exercise: Dir and Help
Learn about the methods Python provides for strings. To see what methods Python provides for a datatype, use the dir and help commands:
Built-in Data Structures
Python comes equipped with some useful built-in data structures, broadly similar to Java’s collections package.
Lists
The items stored in lists can be any Python data type. So for instance we can have lists of lists:
Exercise: Lists
Note: Ignore functions with underscores “_” around the names; these are private helper methods. Press ‘q’ to back out of a help screen.
Tuples
A data structure similar to the list is the tuple, which is like a list except that it is immutable once it is created (i.e. you cannot change its content once created). Note that tuples are surrounded with parentheses while lists have square brackets.
The attempt to modify an immutable structure raised an exception. Exceptions indicate errors: index out of bounds errors, type errors, and so on will all report exceptions in this way.
Sets
A set is another data structure that serves as an unordered list with no duplicate items. Below, we show how to create a set:
Another way of creating a set is shown below:
>>> setOfShapes = {‘circle’, ‘square’, ‘triangle’, ‘circle’}
Next, we show how to add things to the set, test if an item is in the set, and perform common set operations (difference, intersection, union):
Note that the objects in the set are unordered; you cannot assume that their traversal or print order will be the same across machines!
Dictionaries
The last built-in data structure is the dictionary which stores a map from one type of object (the key) to another (the value). The key must be an immutable type (string, number, or tuple). The value can be any Python data type.
Note: In the example below, the printed order of the keys returned by Python could be different than shown below. The reason is that unlike lists which have a fixed ordering, a dictionary is simply a hash table for which there is no fixed ordering of the keys (like HashMaps in Java). The order of the keys depends on how exactly the hashing algorithm maps keys to buckets, and will usually seem arbitrary. Your code should not rely on key ordering, and you should not be surprised if even a small modification to how your code uses a dictionary results in a new key ordering.
As with nested lists, you can also create dictionaries of dictionaries.
Exercise: Dictionaries
Use dir and help to learn about the functions you can call on dictionaries.
Writing Scripts
Now that you’ve got a handle on using Python interactively, let’s write a simple Python script that demonstrates Python’s for loop. Open the file called foreach.py , which should contain the following code:
The next snippet of code demonstrates Python’s list comprehension construction:
Exercise: List Comprehensions
Write a list comprehension which, from a list, generates a lowercased version of each string that has length greater than five. You can find the solution in listcomp2.py .
Beware of Indendation!
Unlike many other languages, Python uses the indentation in the source code for interpretation. So for instance, for the following script:
But if we had written the script as
there would be no output. The moral of the story: be careful how you indent! It’s best to use four spaces for indentation – that’s what the course code uses.
Tabs vs Spaces
Because Python uses indentation for code evaluation, it needs to keep track of the level of indentation across code blocks. This means that if your Python file switches from using tabs as indentation to spaces as indentation, the Python interpreter will not be able to resolve the ambiguity of the indentation level and throw an exception. Even though the code can be lined up visually in your text editor, Python “sees” a change in indentation and most likely will throw an exception (or rarely, produce unexpected behavior).
This most commonly happens when opening up a Python file that uses an indentation scheme that is opposite from what your text editor uses (aka, your text editor uses spaces and the file uses tabs). When you write new lines in a code block, there will be a mix of tabs and spaces, even though the whitespace is aligned. For a longer discussion on tabs vs spaces, see this discussion on StackOverflow.
Writing Functions
As in Java, in Python you can define your own functions:
Rather than having a main function as in Java, the __name__ == '__main__' check is used to delimit expressions which are executed when the file is called as a script from the command line. The code after the main check is thus the same sort of code you would put in a main function in Java.
Save this script as fruit.py and run it:
Advanced Exercise
Write a quickSort function in Python using list comprehensions. Use the first element as the pivot. You can find the solution in quickSort.py .
Object Basics
Although this isn’t a class in object-oriented programming, you’ll have to use some objects in the programming projects, and so it’s worth covering the basics of objects in Python. An object encapsulates data and provides functions for interacting with that data.
Defining Classes
The FruitShop class has some data, the name of the shop and the prices per pound of some fruit, and it provides functions, or methods, on this data. What advantage is there to wrapping this data in a class?
1. Encapsulating the data prevents it from being altered or used inappropriately,
2. The abstraction that objects provide make it easier to write general-purpose code.
Using Objects
So how do we make an object and use it? Make sure you have the FruitShop implementation in shop.py .
We then import the code from this file (making it accessible to other scripts) using import shop , since shop.py is the name of the file. Then, we can create FruitShop objects as follows:
Copy
import shop
fruitPrices = {'apples': 1.00, 'oranges': 1.50, 'pears': 1.75} berkeleyShop = shop.FruitShop(shopName, fruitPrices) applePrice = berkeleyShop.getCostPerPound('apples') print(applePrice) print('Apples cost $%.2f at %s.' % (applePrice, shopName))
otherName = 'the Stanford Mall' otherFruitPrices = {'kiwis': 6.00, 'apples': 4.50, 'peaches': 8.75} otherFruitShop = shop.FruitShop(otherName, otherFruitPrices) otherPrice = otherFruitShop.getCostPerPound('apples') print(otherPrice)
print('Apples cost $%.2f at %s.' % (otherPrice, otherName)) print("My, that's expensive!")
This code is in shopTest.py ; you can run it like this:
Copy
Apples cost $4.50 at the Stanford Mall.
My, that's expensive!
So what just happended? The import shop statement told Python to load all of the functions and classes in shop.py . The line berkeleyShop = shop.FruitShop(shopName, fruitPrices) constructs an instance of the FruitShop class defined in shop.py, by calling the __init__ function in that class. Note that we only passed two arguments in, while __init__ seems to take three arguments:
(self, name, fruitPrices) . The reason for this is that all methods in a class have self as the first argument. The self variable’s value is automatically set to the object itself; when calling a method, you only supply the remaining arguments. The self variable contains all the data ( name and fruitPrices ) for the current specific instance (similar to this in Java). The print statements use the substitution operator (described in the Python docs if you’re curious).
Static vs Instance Variables
The following example illustrates how to use static and instance variables in Python.
Now use the class as follows:
More Python Tips and Tricks
This tutorial has briefly touched on some major aspects of Python that will be relevant to the course. Here are some more useful tidbits:
Troubleshooting
These are some problems (and their solutions) that new Python learners commonly encounter.
Problem: ImportError: No module named py
Solution: For import statements with import <package-name> , do not include the file extension
(i.e. the .py string). For example, you should use: import shop NOT: import shop.py
Solution: To access a member of a module, you have to type MODULE NAME.MEMBER NAME , where
MODULE NAME is the name of the .py file, and MEMBER NAME is the name of the variable (or function) you are trying to access.
Problem: TypeError: ‘dict’ object is not callable
Solution: Dictionary looks up are done using square brackets: [ and ]. NOT parenthesis: ( and ).
Problem: ValueError: too many values to unpack
Solution: Make sure the number of variables you are assigning in a for loop matches the number of elements in each item of the list. Similarly for working with tuples.
For example, if pair is a tuple of two elements (e.g. pair =('apple', 2.0) ) then the following code would cause the “too many values to unpack error”:
Solution: Finding length of lists is done using len(NAME OF LIST) .
Problem: Changes to a file are not taking effect.
Solution:
1. Make sure you are saving all your files after any changes.
2. If you are editing a file in a window different from the one you are using to execute python, make sure you reload(_YOUR_MODULE_) to guarantee your changes are being reflected. reload works similarly to import .
More References
The place to go for more Python information: www.python.org
A good reference book: Learning Python (From the UCB campus, you can read the whole book online)
Autograding
To get you familiarized with the autograder, we will ask you to code, test, and submit solutions for three questions.
You can download all of the files associated the autograder tutorial as a zip archive: tutorial.zip (note this is different from the zip file used in the UNIX and Python mini-tutorials, python_basics.zip). Unzip this file and examine its contents:
This contains a number of files you’ll edit or run: addition.py : source file for question 1 buyLotsOfFruit.py : source file for question 2 shop.py : source file for question 3
shopSmart.py : source file for question 3 autograder.py : autograding script (see below) and others you can ignore:
test_cases : directory contains the test cases for each question grading.py : autograder code testClasses.py : autograder code tutorialTestClasses.py : test classes for this particular project projectParams.py : project parameters
The command python autograder.py grades your solution to all three problems. If we run it before editing any files we get a page or two of output:
Looking at the results for question 1, you can see that it has failed three tests with the error message “add(a, b) must return the sum of a and b”. The answer your code gives is always 0, but the correct answer is different.
We’ll fix that in the next tab.
Question 1: Addition
Now rerun the autograder (omitting the results for questions 2 and 3):
Question 2: buyLotsOfFruit function
Add a buyLotsOfFruit(orderList) function to buyLotsOfFruit.py which takes a list of
(fruit,pound) tuples and returns the cost of your list. If there is some fruit in the list which doesn’t appear in fruitPrices it should print an error message and return None . Please do not change the
fruitPrices variable.
test_cases/q2/food_price1.test tests whether:
Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25
Question 3: shopSmart function
Fill in the function shopSmart(orders,shops) in shopSmart.py , which takes an orderList (like the kind passed in to FruitShop.getPriceOfOrder ) and a list of FruitShop and returns the
FruitShop where your order costs the least amount in total. Don’t change the file name or variable names, please. Note that we will provide the shop.py implementation as a “support” file, so you don’t need to submit yours.
Copy
orders1 = [('apples', 1.0), ('oranges', 3.0)] orders2 = [('apples', 3.0)] dir1 = {'apples': 2.0, 'oranges': 1.0} shop1 = shop.FruitShop('shop1',dir1) dir2 = {'apples': 1.0, 'oranges': 5.0} shop2 = shop.FruitShop('shop2', dir2) shops = [shop1, shop2]
test_cases/q3/select_shop1.test tests whether: shopSmart.shopSmart(orders1, shops) == shop1 and test_cases/q3/select_shop2.test tests whether: shopSmart.shopSmart(orders2, shops) == shop2
Submission
In order to submit your project, run python submission_autograder.py and submit the generated token file tutorial.token to the Project 0 assignment on Gradescope.