Unformatted text preview:

6.189 Homework 2 Readings How To Think Like A Computer Scientist: Wednesday - chapter 3 and Appendix A (all), 6.5 - 6.9. Thursday - chapters 7 & 8 (all). 6.01 Fall 2010 Course Notes: Wednesday - sections 2.1, 2.2, and 2.3 (up to the heading ‘Lists’). Thursday - pages 33-37 (sections ‘Lists’, ‘Iterations over lists’, ‘List Comprehensions’). What to turn in Turn in a printout of your code exercises stapled to your answers to the written exercises at 3 PM on Friday, January 7th. Exercise 2.0 – Print vs Return Note: This exercise is in section 2.2 of the 6.01 Course Notes. If you’ve already gone through it, you may skip this. This isn’t really an exercise, just an important bit of reading. Download the template file homework 2.py. In it these two functions are defined: def f1(x): print x + 1 def f2(x): return x + 1 Run this code in the shell. What happens when we call these functions? >>> f1(3) 4 >>> f2(3) 4 It looks like they behave in exactly the same way. But they really don’t. Try this: 1>>> print f1(3) 4 None >>> print f2(3) 4 In the case of f1, the function, when evaluated, prints 4; then it returns the value None, which is printed by the Python shell. In the case of f2, it doesn’t print anything, but it returns 4, which is printed by the Python shell. Finally, we can see the difference here: >>> f1(3) + 1 4 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unsupported operand type(s) for +: ’NoneType’ and ’int’ >>> f2(3) + 1 5 In the first case, the function doesn’t return a value, so there’s nothing to add to 1, and an error is generated. In the second case, the function returns the value 4, which is added to 1, and the result, 5, is printed by the Python read-eval-print loop. The book How To Think Like A Computer Scientist was translated from a version for Java, and it has a lot of print statements in it, to illustrate programming concepts. But for just about everything we do, it will be returned values that matter, and printing will be used only for debugging, or to give information to the user. Print is very useful for debugging. It’s important to know that you can print out as many variables and strings as you want in one line, when they are separated by commas. Try this: >>> x = 100 >>> print ’x:’, x, ’x squared:’, x*x, ’sqrt(x):’, x**0.5 x: 100 x squared: 10000 sqrt(x): 10.0 Exercise 2.1 – Defining A Function Recall how we define a function using def, and how we pass in parameters. In homework 2.py (download this from the website if you haven’t yet), transform your code from exercise 1.7 (the rock, paper, scissors game) into a function that takes parameters, instead of asking the user for input. Make sure to return your answer, rather than printing it. For this, and all future exercises, include at least 3 test cases below your code. Exercise 2.2 – Writing Simple Methods In this problem you’ll be asked to write two simple methods (method is an interchangeable term for ‘function’). Be sure to test your functions well, including at least 3 test cases for each method. Do your work in homework 2.py. 1. Write a method is divisible that takes two integers, m and n. The method returns True if m is divisible by n, and returns False otherwise. Test cases for this function are included for you; look at the conditions that they test and try to make sure your future test cases are comprehensive. 2� � 2. Imagine that Python doesn’t have the != operator built in. Write a method not equal that takes two parameters and gives the same result as the != operator. Obviously, you cannot use != within your function! Test if your code works by thinking of examples and making sure the output is the same for your new method as != gives you. Exercise 2.3 – Math Module In this exercise, we will play with some of the functions provided in the math module. A module is a Python file with a collection of related functions. To use the module, you need to add the following line at the top of your program, right underneath the comments with your name: import math Example: if you want to find out what is sin(90◦), we first need to convert from degrees to radians and then use the sin function in the math module: radians = (90.0 / 360.0) * 2 * math.pi print math.sin(radians) You can do this work in the interpreter by typing import math and then these lines. For mathematical functions, you can generally call math.func, where func is whatever function you want to call. For example, if you want the sine of an angle a (where a is in radians), you can call math.sin(a). For logarithms, the function math.log(n) calculates the natural logarithm of n. You can calculate the log of any base b (as in logb(n)) using math.log(n, b). The math module even includes constants such as e (math.e) and π (math.pi). Documen-tation for the math module is available at http://docs.python.org/release/2.6.6/library/math.html Many computations can be expressed concisely using the “multadd” operation, which takes three operands and computes a ∗ b + c. One of the purposes of this exercise is to practice pattern-matching: the ability to recognize a specific problem as an instance of a general category of problems. In the last part, you get a chance to write a method that invokes a method you wrote. Whenever you do that, it is a good idea to test the first method carefully before you start working on the second. Otherwise, you might find yourself debugging two methods at the same time, which can be very difficult. 1. Write a function multadd that takes three parameters, a, b and c. Test your function well before moving on. 2. Underneath your function definition, compute the following values using multadd and print out the result: � π � cos( π 4 ) • angle test = sin4+ 2 276 • ceiling test = 19 + 2 log7(12) Hint: If you are unfamiliar with the notation ��, this represents the ceiling of a number. The ceiling of some float x means that we always “round up” x. For example, �2.1� = �2.9� = 3.0. Look at the math module documentation for a way to do this! If everything is working correctly, your output should look like: sin(pi/4) + cos(pi/4)/2 is: 1.06066017178 ceiling(276/19) + 2 log_7(12) is: 17.5539788165 33.


View Full Document

MIT 6 189 - Homework 2

Download Homework 2
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Homework 2 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Homework 2 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?