ICS 31 • DAVID G. KAY • UC IRVINE • WINTER 2013

Lab Assignment 2

This assignment is due at the end of lab on Friday, January 18.

Preparation (Do this part individually, before coming to lab)

(1) If you're just getting enrolled in the class, do everything on the course refrence sheet (the syllabus) under the heading "What to do this week to get started in ICS 31." This includes registering yourself at checkmate.ics.uci.edu and piazza.com, filling out the questionnaire at eee.uci.edu/survey/ics31.w13.q, and turning in your photo to your TA.

(2) Read sections 2.3–2.6 of the Perkovic text, trying the practice problems (before looking at the solutions).

[Reading note: At the beginning of section 2.3, the the list of pet names is homogeneous—all the items are of the same type, strings. Next, the author shows you a heterogenous list—one with items of various types. In our class, we will use lists only for homogeneous data (so, for example, we can apply the same operation to every item on a list); for heterogeneous collections of data, we will use namedtuples (as discussed in class).]

Why have a fractions module when we could just use float numbers? The book mentions situations where you have very large or very small numbers but need to calculate precisely. A related situation occurs when you need to calculate with values like 1/3 that cannot be represented precisely as a decimal number. In a long chain of computations, the difference between 0.33333333 and 1/3 can build up into a significant value; that's called a roundoff error. If you use the fraction library for those computations and convert to a float only at the very end, you avoid the potential for roundoff errors.

Section 2.6 introduces Python's turtle graphics library. Play around with it a little before coming to lab.

(3) Read sections 3.3 and 3.5 of the Perkovic textbook. (You can skip the section in the middle of page 72; it's more confusing than helpful.) We'll get to the other sections soon and if you have some time, you can go ahead and read the chapter in order. But we're going to be talking about these two sections first. As you read, do practice problems 3.8, 3.9, 3.11 (for the average function), 3.14, and 3.15.

[Reading note: The author uses the term "user-defined functions." A more modern, more accurate term would be "programmer-defined functions." Decades ago, a computer user was a person who wrote software, but today a user is an "end user" who rarely if ever writes any code.]

Functions might be the single most important concept in first-quarter programming. They're not the only important concept—we need a lot of concepts to write useful programs—but encapsulating operations into a named function and then using that function as a component of still larger functions, that's a basis of all software development. Functions are also sometimes called procedures, methods, subroutines, or subprograms; sometimes those terms are used in subtly different ways, but sometimes not.

(4) Go back and read the assignment advice again, especially about the "three-minute rule."

(5) Read through the Lab Work part of this assignment before you come to lab on Monday, just to get an idea of what you'll be doing with your partner.

 

Lab Work (Do this part with your partner in lab)

(a) Choose a partner for this assignment and make sure the TA knows who your partner is. Remember that you'll choose a different partner for each lab assignment, so you'll work with this partner only this week. Make sure you know your partner's name (first and last) and contact information (Email or cellphone or whatever) in case one of you can't make it to lab.

(b) For this assignment, you will create a Python file called lab2.py. Type your answers to all the parts of this assignment into this file; non-Python text can be in comments or multi-line (triple-quoted) strings.

On the first line of the file type a comment withthe names and IDs of both partners and some other identifying information, like this:

#  Paula Programmer 11223344 and Andrew Anteater 44332211.  ICS 31 Lab sec 7.  Lab asst 2.

Python code in your file should produce the specified results when you run the file. When you've finished the assignment, you'll submit this file via Checkmate. (It's a good idea if each partner keeps a copy of the lab work at the end of each session, just in case someone can't make it to the next lab.)

(c) On the first day of class, we wrote and ran this sequence of statements:

hours = int(input('How many hours?'))
print('This many hours:', hours)
rate = int(input('How many dollars per hour?  '))
print('This many dollars per hour:  ', rate)
print('Weekly salary:  ', hours * rate)

(c.1) Copy this code and paste it into your lab2.py file; then run it to make sure it works as you expect.

Then modify the code to print a dollar sign before each dollar amount. (For now, don't worry about the precise spacing or the precise number of digits after the decimal point; we'll learn how to specify those later.)

(c.2) Write a new sequence of statements that, when executed, might produce results that look like this (where the bold-faced text would by typed by the user):

Hello.  What is your name?  Alice Anteater
Hello, Alice Anteater
It's nice to meet you.  
How old are you?  19
Next year you will be 20 years old.
Good-bye!

The foregoing may be enough to get you going on this problem. But here are a couple of tips and bits of advice that may help give you a boost:

(d) The Copenhagen Chamber of Commerce has hired you to write a program that will convert foreign currencies to the equivalent amount in Danish krone. Your program will prompt the user to input four items, in this order: The name of the business using the program, the number of Euros that business has, the number of British pounds, and the number of U.S. dollars.

Your program will produce as output the business name, a list of how much of each currency the business has (in both the foreign amount and the Danish krone equivalent) with one foreign currency per line, and the business's total amount of money in krone.

Assume that the following exchange rates are in effect: One Euro is 7.46 krone, one British pound is 9.02 krone, one U.S. dollar is 5.59 krone. [Implementation note: This is one of those situations where hard-coding constants is appropriate, since our program is not going to look up the actual exchange rates on the internet. (That may be something you'll do in ICS 32, though.) At the top of your Python code you should have three assignment statements that define these constants; they should look like this: KRONE_PER_EURO = 7.46 . Then you will use those defined constants where appropriate in your program's calculations.]

For example, if the business name is Tycho Brahe Enterprises and it has €100, £200, and $1000, the displayed results would be as shown below (with the user's input shown in boldface):

Please provide this information:
Business name:  Tycho Brahe Enterprises
Number of euros:  100
Number of pounds:  200
Number of dollars:  1000

Copenhagen Chamber of Commerce
Business name:   Tycho Brahe Enterprises
100 euros is 746.0 krone
200 pounds is 1804.0 krone
1000 dollars is 5590.0 krone

Total krone:   8140.0

(Don't worry about the precise spacing or number of digits after the decimal point; we'll learn how to control that later on.)

(e) [This part of the assignment depends on material we will cover in class on Tuesday; you won't be able to do it before then.] Given this code (which you may copy and paste into your file to work with):

from collections import namedtuple
Book = namedtuple('Book', 'title author year price')
favorite = Book('Adventures of Sherlock Holmes',
                'Arthur Conan Doyle', 1892, 21.50)
another = Book('Memoirs of Sherlock Holmes', 
               'Arthur Conan Doyle', 1894, 23.50)
still_another = Book('Return of Sherlock Holmes',
                     'Arthur Conan Doyle', 1905, 25.00)

Write expressions using the variables favorite, another, and still_another that evaluate to each of the following:

(e.1) the title of the book in the variable still_another .

(e.2) the price of the book Memoirs of Sherlock Holmes

(e.3) the average price of all three books

(e.4) True or false, based on whether the publication year of the book in the variable favorite is before 1900.

Next, write two assignment statements:

(e.5) Change the price of the book Return of Sherlock Holmes to $26.00

(e.6) Change the price of the book Return of Sherlock Holmes by increasing it 20%

(f) Define a namedtuple called Animal for animals in a zoo, with fields for the animal's name, its species, its age, its weight, and its favorite food.

Then define variables to hold (i) an elephant called Jumbo that's 50 years old, weighs 1000 kg, and eats peanuts, and (ii) a platypus named Perry that's 7 years old, weighs 1.7 kg, and eats shrimp.

Finally, write a boolean expression whose value is true if the weight of the animal represented by the first variable is less than the weight of the animal represented by the second variable.

You might be asking yourself why it's useful to write an expression like that when we know from looking at the data that Jumbo weighs more than Perry. The answer is that variables can vary; that is, we might have a program where different animals, or different weights for the same animals, get stored in the variables you defined. Because the expression you wrote uses whatever value the variable currently has, we can re-use that same expression for whatever animals we want, so long as we store those animals' information in the variables you defined and used in your expression. It's good to write general, versatile code like this.

(g) Add this statement to your book code:

booklist = [favorite, another, still_another]

(g.1) Write a boolean expression whose value is true if the first book on the list [remember what the index number of the first book is] is cheaper than the second book on the list (and false otherwise). (In your lab2.py file, just print this expression.)

(g.2) Write (and print) another boolean expression whose value is true if the first book on the list is more recently published than the last book on the list. Don't write this using booklist[2] for the last book; instead, use an expression whose value would be the last book on the list, no matter how long the list is.

(h) In class we discussed how a programming language gives us predefined or built-in "building blocks" (like ints and strings, and like + and len()) and then gives us ways to combine them into more complicated and powerful features that we can use as we develop our software. Namedtuples are an example of this; after we create a Book, our version of Python has a new type of data we can use in our programs.

One theme of this course is how we can build and work with data structures in this way.

Here we create a list of seven restaurants, calling it RC (for "restaurant collection"). Copy this code into your lab2.py file.

from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
# Restaurant attributes: name, kind of food served, phone number, best dish, price of that dish
RC = [
    Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50),
    Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50),
    Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50),
    Restaurant("Jitlada", "Thai", "324-4433", "Paht Woon Sen", 15.50),
    Restaurant("Nola", "New Orleans", "336-4433", "Jambalaya", 5.50),
    Restaurant("Noma", "Modern Danish", "337-4433", "Birch Sap", 35.50),
    Restaurant("Addis Ababa", "Ethiopian", "337-4453", "Yesiga Tibs", 10.50) ]

For each of the values described below, write a Python expression using RC that produces that value (and enclose it in a print statement in your lab2.py file).

(h.1) The name of the third restaurant on the list (remember that the third restaurant is not number 3)

(h.2) True or False, whether the first and the fourth restaurants serve the same kind of food

(h.3) The price of (the best dish at) the last restaurant on the list (write this one so that it works for lists of any length, not just 7)

(h.4) The list of restaurants, arranged alphabetically by restaurant name (you'll need one statement before the print statement)

(h.5) The best dish at the restaurant that's alphabetically last (you'll need an extra statement here, too; your solution should work for lists of any length)

(h.6) A new list containing 4 restaurants: the first two alphabetically and the last two alphabetically (this one should work for lists of any length; you may need a couple of extra statements and the extend() method [see help(list)])

(i) At the end of Chapter 2, do exercises 2.26 and 2.27.

Next do exercise 2.28. For each of the shapes, the line drawing statement is the same. What statement has to change for each different shape? Can you come up with an expression that uses a variable (call it sides) to compute the number in that changing statement, whatever value (of 3 or more) sides has? You may consult outside of your partnership on this issue, but think it through; don't just grab the answer.

Pick one of 2.29 or 2.30. Then pick one of 2.32, 2.33, 2.34, 2.35, or 2.36

(j) Write a series of turtle graphics statements to draw an eye. You should have at least the basic eye shape with a pupil and an iris; feel free to make it as much fancier as you like. Show your final results to your tutor and TA to impress them.

(k) Remember that each partner must complete a partner evaluation form and submit it individually. Do this by connecting to eee.uci.edu and choosing the Survey tool for your lab section of ICS 31. Make sure you know your partner's name, first and last, so you can evaluate the right person. Please complete your evaluation by the end of the day on Friday, or Saturday morning at the latest. It only takes a couple of minutes and not doing it hurts your participation score.

What to turn in: Submit via Checkmate your lab2.py file containing your solutions to parts (c) through (j). It would be an excellent idea to go back and re-read those parts carefully now, to make sure you've completed all the steps specified. It would also be an excellent idea to run your file one last time to make sure all the correct results appear, with no error messages. (If you run into problems, it's probably because you have more than one function with the same name. Change one of the names [everywhere necessary] and try to Run again.)

Also remember that each student must complete a partner evaluation form by logging in to eee.uci.edu and selecting the Survey tool; these evaluations contribute to your class participation score. Get in the habit of doing this every week on Friday after you've submitted your assignment; the survey closes on Saturday.

 

Written by David G. Kay in Fall 2012 for ICS 31. Modified by David G. Kay, Winter 2013.



David G. Kay, kay@uci.edu
Sunday, January 13, 2013 5:52 PM