MIT6 189IAP11 hw2
MIT6 189IAP11 hw2
MIT6 189IAP11 hw2
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.
>>> 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 doesnt print anything, but it returns 4, which is printed by the Python shell. Finally, we can see the dierence 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 rst case, the function doesnt return a value, so theres 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. Its 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
2. Imagine that Python doesnt 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.
3. Write a new function called yikes that has one argument and uses the multadd function to calculate the following:
xex + (1 ex )
There are two dierent ways to raise e to a power- check out the math module documentation. Be sure to
return the result! Try x=5 as a test; your answer should look like:
yikes(5) is 1.0303150673.
4. Run this list comprehension in your prompt: [x+y for x in [10,20,30] for y in [1,2,3]] Figure out what is going on here, and write a nested for loop that gives you the same result. Make sure what is going on makes sense to you!
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.