Think Python/Answers
Think Python/Answers
Base 8: 00 01 02 03 04 05 06 07 10 11 12 13 14 15 16
17 20 21 22 23 24 Base 10: 00 01 02 03 04 05 06 07 08
09 10 11 12 13 14 15 16 17 18 19 20
Chapter 1
1.1
Exercise 1.4
>>>
print
02132
1114
>>>
(2*512)+(1*64)+(3*8)+(2*1)
1114
>>>
>>> 10 / 1.61 # Convert kilometers to miles
6.2111801242236018 >>> (43 * 60) + 30 # Convert
time to seconds 2610 >>> 2610 / 6.2111801242236018
# what is your average time (seconds) per mile 2.2 Exercise 2.4
420.21000000000004 >>> 420.21000000000004 /
60 # what is your average time (minutes) per mile The volume of a sphere with radius r is 4/3 r3 . What is
7.0035000000000007 >>> 60 / 7.0035000000000007 the volume of a sphere with radius 5?
# Miles per hour 8.5671449989291055 How
about >>> 10 / 43.5 # avg kilometers per minute >>> pi = 3.1415926535897931 >>> r = 5
0.22988505747126436 >>> 0.22988505747126436*60 >>> 4/3*pi*r**3 # This is the wrong answer
# kilometers per hour 13.793103448275861 >>> 392.69908169872411 >>> r = 5.0 # Radius can be
13.793103448275861 / 1.61 # convert to M.P.H a oat here as well, but is not _necessary_. >>>
8.567144998929106 or a one-liner >>> (10 / 1.61) 4.0/3.0*pi*r**3 # Using oats give the correct answer
/ (43.5 / 60) # (distance in miles) / (time in hours) 523.59877559829886 >>>
8.567144998929106 # miles/hour making it 'pretty' & Suppose the cover price of a book is $24.95, but bookexploring how print works.... >>> print round((10 / stores get a 40% discount. Shipping costs $3 for the rst
1.61) / (43.5 / 60), 2), 'mph' # (distance in miles)/(time copy and 75 cents for each additional copy. What is the
in hours) rounded to 2 places 8.57 mph
total wholesale cost for 60 copies?
$24.95 Cost $9.98 Discount per book $14.97 Cost
per book after discount 60 Total number of books
$898.20 Total cost not inc delivery $3.00 First book
2 Chapter 2
delivery 59 Remaining books $0.75 Delivery cost
for extra books $44.25 Total cost for extra books
2.1 Exercise 2.1
$47.25 Total Delivery cost $945.45 Total Bill This
answer is wrong because 40.0/100.0 return wrong
If you type an integer with a leading zero, you might get value 0.40000000000000002 for more info see
a confusing error:
IEEE 754 (Standard for Floating-Point Arithmetic)
>>>
(24.95-24.95*40.0/100.0)*60+3+0.75*(60-1)
>>> zipcode = 02492 ^ SyntaxError: invalid token
945.44999999999993 >>> 24.95*0.6*60+0.75*(60Other number seem to work, but the results are bizarre: 1)+3 945.45
>>> zipcode = 02132 >>> print zipcode 1114
If I leave my house at 6:52 am and run 1 mile at an easy
So python is assuming you want to convert an octal num- pace (8:15 per mile), then 3 miles at tempo (7:12 per
ber to a decimal number. In the base 8 numbering system mile) and 1 mile at easy pace again, what time do I get
where valid numbers are 0, 1, 2, 3, 4, 5, 6 and 7.
home for breakfast?
1
3 CHAPTER 3
Answer: 7:30 am
How I did it:
>>> start = (6*60+52)*60 >>> easy = (8*60+15)*2
>>> fast = (7*60+12)*3 >>> nish_hour = (start + easy
+ fast)/(60*60.0) >>> nish_oored = (start + easy +
fast)//(60*60) #int() function can also be used to get
integer value, but isn't taught yet. >>> nish_minute
= (nish_hour - nish_oored)*60 >>> print 'Finish
time was %d:%d' % (nish_hour,nish_minute) Finish
time was 7:30 *** ANOTHER WAY *** start_time_hr
= 6 + 52 / 60.0 easy_pace_hr = (8 + 15 / 60.0 )
/ 60.0 tempo_pace_hr = (7 + 12 / 60.0) / 60.0 running_time_hr = 2 * easy_pace_hr + 3 * tempo_pace_hr
breakfast_hr = start_time_hr + running_time_hr breakfast_min = (breakfast_hr-int(breakfast_hr))*60 breakfast_sec= (breakfast_min-int(breakfast_min))*60 print
('breakfast_hr', int(breakfast_hr) ) print ('breakfast_min',
int (breakfast_min) ) print ('breakfast_sec', int (breakfast_sec) ) >>>
3
3.1
Chapter 3
Exercise 3.3
3.2
Exercise 3.5
3
print_block() ----------------------- # mteodor def
draw_line(bar, middle = ' ', repeat = 2, lenght = 2):
""" Draw a single line like this: [ (B M*repeat)*lenght
B] """ for k in range(lenght): print("%s %s " % (bar,
middle*repeat), end='') print(bar) def draw_grid(lenght
= 2, height = 2, width = 2): """ Draw a grid like this: +
-- + -- + | | | | | | + -- + -- + | | | | | | + -- + -- + where: *
lenght x heigth are the table size * width is the size of
a cell/column """ for i in range(height): draw_line('+',
'-', width, lenght) for j in range(lenght): draw_line('|',
' ', width, lenght) draw_line('+', '-', width, lenght)
draw_grid(4, 4, 3)
4
4.1
Chapter 4
6 Chapter 9
6.1 Exercise 9.1
n = open('words.txt') for line in n: word = line.strip()
if len(word) > 20: print (word)
4.3 Exercise 1
6.3 Exercise 9.3
7 Chapter 10
7.1 Exercise 10.1
4.3
4.3 Exercise 3
7.3
Exercise 10.3
CHAPTER 12
Exercise 11.3
7.4
Exercise 10.4
Write a function called middle that takes a list and returns 8.4 Exercise 11.4
a new list that contains all but the rst and last elements.
Modify reverse_lookup so that it builds and returns a list
>>> def middle(x): res = [] i = 1 while i <= len(x)2:
of all keys that map to v, or an empty list if there are none.
res.append(x[i]) i += 1 return res
def reverse_lookup(d,v): l = list() for c in d: if d[c] ==
v: l.append(c) return l
This can also be done simply with a slice.
>>> def middle(x): return x[1:1]
9 Chapter 12
7.5
Exercise 10.5
9.1 Exercise 12.1
8
8.1
Chapter 11
Exercise 11.1
11.2
Exercise 14.5
d=dict_of_signatures_and_words()):
db
=
shelve.open(lename) for key, values in d.items():
if len(values)>1: for index, value in enumerate(values):
db[value]=values[:index]+values[index+1:] db.close()
or
def print_contents_of_db(lename='anagrams): db =
from random import shue def sort_by_length(words): shelve.open(lename, ag='r') for key in sorted(db):
r = [] d = dict() for word in words: d.setdefault(len(word), print(key.rjust(12), '\t<==>\t', ', '.join(db[key]))
[]).append(word) for key in sorted(d, reverse=True): if db.close() db_of_anagrams() print_contents_of_db()
len(d[key]) > 1: shue(d[key]) r.extend(d[key]) return r
9.3
Exercise 12.3
11
Chapter 14
11.1
Exercise 14.3
13 Chapter 16
13
CHAPTER 16
or
13.2
Exercise 16.2
or
# Solution for Python3 # Replace '//' by '/' for Python2
def increment(time, seconds): time.second += seconds time.minute += time.second//60 time.hour +=
time.minute//60 time.second %= 60 time.minute %= 60
time.hour %= 24
# A dierent way of going about it def increment(time,
seconds): # Converts total to seconds, then back to
a readable format time.second = time.hour*3600 +
time.minute*60 + time.second + seconds (time.minute,
time.second)
=
divmod(time_in_seconds,
60)
(time.hour, time.minute) = divmod(time.minute,
60)
13.4
Exercise 16.4
13.5
Exercise 16.5
Write a class denition 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.
class Date(object): """represents a date. attributes:
day, month, year""" def print_date(date): # German date format print('{}.{}.{}'.format(date.day,
date.month, date.year)) def is_leap_year(year): #
http://en.wikipedia.org/wiki/Leap_year#Algorithm if
year % 4 == 0: if year % 100 == 0: if year % 400 ==
0: return True return False return True return False
def month_list(year): if is_leap_year(year): return
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def
days_of_year(year): if is_leap_year(year): return 366
return 365 def date_to_int(date): days = 0 for year
in range(1, date.year): days += days_of_year(year)
month_days = month_list(date.year) for month in
range(1, date.month): days += month_days[month - 1]
days += date.day - 1 return days def int_to_date(days):
date = Date() date.year = 1 next_days = 365 while
days >= next_days: date.year += 1 days -= next_days
next_days = days_of_year(date.year) date.month = 1
next_days = 31 month_days = month_list(date.year)
while days >= next_days: date.month += 1 days -=
next_days next_days = month_days[date.month - 1]
date.day = days + 1 return date def increment_date(date,
n): days = date_to_int(date) return int_to_date(days
+ n) d1 = Date() d1.day, d1.month, d1.year = 8,
7
3, 2012 print_date(d1) d2 = increment_date(d1, 7) to get a list of the colors. from color_list import
print_date(d2)
COLORS from visual import scene, sphere def
all_colors(colors_string=COLORS): """Extract a list
of unique RGB-tuples from COLORS. The tuples look
like (r, g, b), where r, g and b are each integers in
[0, 255]. """ # split the string into lines and remove
13.8 Exercise 16.8
irrelevant lines lines = colors_string.split('\n')[2:2]
1. Use the datetime module to write a program that gets # split the individual lines and remove the names
numbers_only = [line.split()[:3] for line in lines] # turn
the current date and prints the day of the week.
strings into ints and rgb-lists into tuples rgb_tuples = [tufrom datetime import date def current_weekday(): i =
ple([int(s) for s in lst]) for lst in numbers_only] # return
date.today() print i.strftime('%A') current_weekday()
a list of unique tuples return list(set(rgb_tuples)) def
make_spheres(color_tuples=all_colors()): scene.range
2. Write a program that takes a birthday as input and = (256, 256, 256) scene.center = (128, 128, 128)
prints the users age and the number of days, hours, min- for (r, g, b) in color_tuples: sphere(pos=(r, g, b),
utes and seconds until their next birthday.
radius=7, color=(r/255., g/255., b/255.)) if __name__
# Python3 solution. Replace input by raw_input == '__main__': make_spheres()
for Python2.
from datetime import datetime def
time_until_birthday(): dob_input = input(('Please enter
the date of your birth in ' 'the format mm/dd/yyyy":
')) dob = datetime.strptime(dob_input, '%m/%d/%Y')
now = datetime.now() if now > datetime(now.year,
dob.month, dob.day): age = now.year - dob.year
next_year = True else: age = now.year - dob.year
- 1 next_year = False time_to_birthday = datetime(now.year + next_year, dob.month, dob.day) now days = time_to_birthday.days hours, remainder
= divmod(time_to_birthday.seconds, 3600) minutes,
seconds = divmod(remainder, 60) print("\nYou are {}
years old..format(age)) print((You have {0} days, {1}
hours, {2} minutes and {3} " seconds left until your
next birthday.).format( days, hours, minutes, seconds))
time_until_birthday()
15 Chapter 3.5
15.1 calculator
15.2 palindrome
15.3
16
def sum_of_n_numbers(number):
if(number==0):
return
0
else:
return
number
+
sum_of_n_numbers(number-1)
num
=
raw_input(Enter
a
number:")
num=int(num)
sum
=
sum_of_n_numbers(num)
print
sum
###another answer in case of while loops def
sum_of_Digits(number):
sum=0 while number>0:
digit=number%10 sum=sum+digit number=number/10
return sum num=raw_input(enter the number)
num=int(num)
sum_of_digits=sum_of_Digits(num)
print sum_of_digits
15.4
Exercise 18.5
APPENDIX B
16 Appendix B
16.1 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 its there, or None if its not.
from bisect import bisect_left def bisection(sorted_list,
item):
i = bisect_left(sorted_list, item) if i <
len(sorted_list) and sorted_list[i] == item: return i
else: return None if __name__ == '__main__': a
= [1, 2, 3] print(bisection(a, 2)) # expect 1 b = [1,
16.1
Exercise B.3
10
17
17
17.1
17.2
Images
17.3
Content license