Think Python/Answers

Chapter 1
See below for Chapter 1 exercises.

Exercise 1.2
1.) How many seconds are there in 42 minutes 42 seconds?

>>> (42 * 60) + 42

2562 seconds

2.) How many miles are there in 10 kilometers? Hint there are 1.61 kilometers in a mile.

>>> 10/1.61

6.21 miles

3.) If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are about 1.61 kilometers in a mile.)

>>> 10 / 1.61                 # convert kilometers to miles

6.211180124223602

>>> (42 * 60) + 42            # convert time to seconds

2562

>>> 2562 / 6.211180124223602 # what is your average time (seconds) per mile

412.482

>>> 412.482 / 60              # what is your average time (minutes) per mile

6.874700000000001

>>> 60 / 6.874700000000001    # miles per hour

8.727653570337614

How about another way

>>> 10 / 42.7                 # avg kilometers per minute

0.23419203747072598

>>> 0.23419203747072598 * 60  # kilometers per hour

14.05152224824356

>>> 14.05152224824356 / 1.61  # convert to M.P.H

8.727653570337614

or a one-liner

>>> (10 / 1.61) / (42.7 / 60)  # (distance in miles) / (time in hours)

8.727653570337614              # miles/hour

Exercise 2.1
If you type an integer with a leading zero, you might get a confusing error:

Other number seem to work, but the results are bizarre:

So python is assuming you want to convert an octal number to a decimal number. In the base 8 numbering system where valid numbers are 0, 1, 2, 3, 4, 5, 6 and 7. Every 8 numbers we increment the left hand columns. This means that the right most column is the number of 'ones'. The one to the left of that is a tally of the number of 'eights', the one next to that is a tally of a full column of 'eight' times the 'eight column' - 64. The one next to that is 64*8 - 512 and so on. For more information read Base Eight math.

That is why zipcode = 02492 is invalid as the digit 9 is not a valid octal number. We can do the conversion manually as follows:

Exercise 2.2
The volume of a sphere with radius $$r$$ is 4/3 &#X3C0; $$r^3$$. What is the volume of a sphere with radius 5?

Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?

Another solution using functions as well as input prompts:

If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

Answer: 7:30 am

How I did it:

Exercise 3.1
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

Alternate Solution Using concatenation and repetition

Exercise 3.3
You can see my solution at http://thinkpython.com/code/grid.py.

Exercise 10.1
Write a function called nested_sum that takes a nested list of integers and add up the elements from all of the nested lists.

Exercise 10.2
Write a function named "capitalize_nested" that takes a nested list of strings and returns a new nested list with all strings capitalized.

Exercise 10.3
Write a function that takes a list of numbers and returns the cumulative sum.

Exercise 10.4
Write a function called middle that takes a list and returns a new list that contains all but the first and last elements.

This can also be done simply with a slice.

Exercise 10.5
Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.

Exercise 11.1
Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

Exercise 11.2
Edit: This was not the exercise I found in my edition of 'Think Python', so I've added my answer in case anyone else is curious: Use get to write histogram more concisely. You should be able to eliminate the if statement.

Exercise 11.3
Dictionaries have a method called keys that returns the keys of the dictionary, in no particular order, as a list. Modify print_hist to print the keys and their values in alphabetical order.

OR

Exercise 11.4
Modify reverse_lookup so that it builds and returns a list of all keys that map to v, or an empty list if there are none.

Exercise 12.1
or

or

or

Exercise 12.2
or

Exercise 16.1
or

Exercise 16.3
or

Exercise 16.7
Write a class definition for a Date object that has attributes day, month and year. Write a function called increment_date that takes a Date object, date, and an integer, n, and returns a new Date object that represents the day n days after date. Hint: “Thirty days hath September...” Challenge: does your function deal with leap years correctly? See wikipedia.org/wiki/Leap_year.

Exercise 16.8
1. Use the datetime module to write a program that gets the current date and prints the day of the week. 2. Write a program that takes a birthday as input and prints the user’s age and the number of days, hours, minutes and seconds until their next birthday.

Exercise 17.8
2.

3. Download http://thinkpython.com/code/color_list.py and use the function read_colors to generate a list of the available colors on your system, their names and RGB values. For each named color draw a sphere in the position that corresponds to its RGB values.

Exercise B.1
Read the Wikipedia page on Big-Oh notation and answer the following questions:

1. ''What is the order of growth of n³ + n²? What about 1000000n³ + n²? What about n³ + 1000000n²?''
 * A: All are O(n³)

2. ''What is the order of growth of (n² + n) · (n + 1)? Before you start multiplying, remember that you only need the leading term.''
 * A: O(n³)

3. If f is in O(g), for some unspecified function g, what can we say about af + b, where a and b are constants?
 * A: a and b are also O(g) since O-notation uses the leading coefficient. Constants are O(1), so they are irrelevant in this case.

4. If f1 and f2 are in O(g), what can we say about f1 + f2?
 * A: Assuming the author means that g in this problem is separate from g the last problem, then O(g) remains unchanged.

5. If f1 is in O(g) and f2 is in O(h), what can we say about f1 + f2?
 * A: f1 + f2 may or may not match the higher order of growth of either O(g) and O(h). If f1 or f2 are the leading coefficients, then f1 + f2 will have the same order of growth as the the largest order of growth of either O(g) or O(h). If that is not the case, then any information about order of growth of f1 + f2 is unknown to us. i.e. It doesn't matter that they are being added.

6. If f1 is in O(g) and f2 is O(h), what can we say about f1 · f2?
 * A: This is different. If f1 and f2 are multiplied (and assuming they each contain an n in them) then O(f1 · f2) has to be O(n) or larger. It could be larger if f1 is n³, for example, but it must at least be O(n).

Exercise B.3
Write a function called bisection that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or None if it’s not.