Think Python/Answers
Contents |
[edit] Chapter 1
[edit] Exercise 1.4
If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile).
>>> 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 420.21000000000004 >>> 420.21000000000004/60 # what is your average time (minutes) per mile 7.0035000000000007 >>> 60/7.0035000000000007 # Miles per hour 8.5671449989291055
Comment: This is not valid, it ONLY works for 43min and 30 seconds to 10km's. Python should have a way to do this the proper way.
In order to do this the proper way, a person must do something like this.
43*60 -> convert the minutes to seconds.
2580+30 -> add the seconds
2610/10 -> divide by distance
261/60 -> change seconds into minutes
4.35 -> is the answer, now you must
.35*60 -> multiply the number after the decimal with 60
21 seconds..
End result = 4.21 minutes per KM, this technique works for all distances and times.
[edit] Chapter 2
[edit] Exercise 2.1
If you type an integer with a leading zero, you might get a confusing error:
>>> zipcode = 02492
^
SyntaxError: invalid token
Other number seem to work, but the results are bizarre:
>>> zipcode = 02132 >>> print zipcode 1114
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.
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
Every 8 numbers we increment the left hand columns. This means that the left most column is the number of 'ones'. The one to the right 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:
>>> print 02132 1114 >>> (2*512)+(1*64)+(3*8)+(2*1) 1114 >>>
[edit] Exercise 2.4
The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5?
>>> pi = 3.1415926535897931 >>> r = 5 >>> 4/3*pi*r**3 # This is the wrong answer 392.69908169872411 >>> r = 5.0 # Radius can be a float here as well, but is not _necessary_. >>> 4.0/3.0*pi*r**3 # Using floats give the correct answer 523.59877559829886 >>>
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?
$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 delivery
59 Remaining books
$0.75 Delivery cost for extra books
$44.25 Total cost for extra books
$47.25 Total Delivery cost
$945.45 Total Bill
This answer is wrong because 40.0/100.0 return wrong value 0.40000000000000002 for more info see IEEE 754 (Standard for Floating-Point Arithmetic)
>>> (24.95-24.95*40.0/100.0)*60+3+0.75*(60-1)
945.44999999999993
>>> 24.95*0.6*60+0.75*(60-1)+3
945.45
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:
>>> start = (6*60+52)*60 >>> easy = (8*60+15)*2 >>> fast = (7*60+12)*3 >>> finish_hour = (start + easy + fast)/(60*60.0) >>> finish_minute = (finish_hour - int(finish_hour))*60 >>> print 'Finish time was %d:%d' % (finish_hour,finish_minute) Finish time was 7:30 >>>
[edit] Chapter 3
[edit] Exercise 3.3
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.
>>> def right_justify(s):
... print (' '*(70-len(s))+s)
...
>>> right_justify('allen')
allen
>>>
[edit] Exercise 3.4
You can see my solution at [http://thinkpython.com/code/grid.py].
""" Solution to Exercise X.X on page X of Think Python Allen B. Downey """ # here is a mostly-straightforward solution to the # two-by-two version of the grid. def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_beam(): print '+ - - - -', def print_post(): print '| ', def print_beams(): do_twice(print_beam) print '+' def print_posts(): do_twice(print_post) print '|' def print_row(): print_beams() do_four(print_posts) def print_grid(): do_twice(print_row) print_beams() print_grid() # here is a less-straightforward solution to the # four-by-four grid def one_four_one(f, g, h): f() do_four(g) h() def print_plus(): print '+', def print_dash(): print '-', def print_bar(): print '|', def print_space(): print ' ', def print_end(): print def nothing(): "do nothing" def print1beam(): one_four_one(nothing, print_dash, print_plus) def print1post(): one_four_one(nothing, print_space, print_bar) def print4beams(): one_four_one(print_plus, print1beam, print_end) def print4posts(): one_four_one(print_bar, print1post, print_end) def print_row(): one_four_one(nothing, print4posts, print4beams) def print_grid(): one_four_one(print4beams, print_row, nothing) print_grid() comment = """ After writing a draft of the 4x4 grid, I noticed that many of the functions had the same structure: they would do something, do something else four times, and then do something else once. So I wrote one_four_one, which takes three functions as arguments; it calls the first one once, then uses do_four to call the second one four times, then calls the third. Then I rewrote print1beam, print1post, print4beams, print4posts, print_row and print_grid using one_four_one. Programming is an exploratory process. Writing a draft of a program often gives you insight into the problem, which might lead you to rewrite the code to reflect the structure of the solution. --- Allen """ print comment
[edit] Chapter 9
[edit] Exercise 9.1
fin = open('words.txt') for line in fin: word = line.strip() if len(word) >= 20: print (word)
[edit] Chapter 10
[edit] Exercise 10.1
Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
>>> def sumlist(x): res = [0]*len(x) i = 0 while i <= len(x)-1: if i == 0: res[0] = x[0] i += 1 else: res[i]=res[i-1]+x[i] i += 1 return res
[edit] Exercise 10.2
Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.
>>> def chop(x): del x[0] del x[len(x)-1] return "none"
Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
>>> def middle(x): res = [] i = 1 while i <= len(x)-2: res.append(x[i]) i += 1 return res
[edit] Chapter 11
[edit] Exercise 11.1
>>>englishdictionary = dict() >>>fin = open('words.txt') >>>line = fin.readline() >>>word = line.strip() >>>def engdicdefine(): index = 0 while index <= 1000: englishdictionary[index] = word i += 1 return englishdictionary
[edit] Exercise 11.2
def histogram(s): d = dict() for c in s: d[c] = 1 + d.get(c, 0) return d
[edit] Exercise 11.4
def reverse_lookup(d,v): l = list() for c in d: if d[c] == v: l.append(c) return l
[edit] Chapter 12
[edit] Exercise 12.1
numbers = (1,2,3) def sumall(numbers): x = 0 for i in numbers: x = x + i print x sumall(numbers)
or
def sumall(*t): x = 0 for i in range(len(t)): x += t[i] return x
or
def sumall(*args): t = list(args) return sum(t)
[edit] Exercise 12.2
import random def sort_by_length(words): t = [] for word in words: t.append((len(word),word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) i=0 final = [] while i <= len(res)-2: if len(res[i]) == len(res[i+1]): y_list = [res[i], res[i+1]] random.shuffle(y_list) final = final + y_list i += 2 else: final.append(res[i]) i += 1 if i == len(res)-1: final.append(res[i]) return final
[edit] Chapter 16
[edit] Exercise 16.1
def print_time(t): print '%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second)
[edit] Exercise 16.2
def is_after(t1, t2): print t1.hour < t2.hour or t1.minute < t2.minute or t1.second < t2.second
[edit] Exercise 16.3
def increment(time, seconds): n = seconds/60 time.second += seconds - 60.0*n time.minute += n m = time.minute/60 time.minute -= m*60 time.hour += m
[edit] Exercise 16.5
class Time(object): """represents the time of day. attributes: hour, minute, second""" time = Time() time.hour = 11 time.minute = 59 time.second = 30 def time_to_int(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time def increment(time, addtime): seconds = time_to_int(time) return int_to_time(seconds + addtime) def print_time (x): print 'The time is %.2d : %.2d : %.2d' % (x.hour, x.minute, x.second) print_time (time) newtime = increment (time, 70) print_time (newtime)
[edit] Chapter 3.5
[edit] calculator
#recursion or recursive print "\n INDEX\n""\n C=1 for addition\n""\n C=2 for substraction\n""\n C=3 for multiplication\n""\n C=4 for division\n""\n C=5 for to find modulus\n""\n C=6 to find factorial\n" C=input("Enter your choice here: ") def add(x,y): c=x+y print x,"+",y,"=",c def sub(x,y): c=x-y print x,"-",y,"=",c def mul(x,y): c=x*y print x,"*",y,"=",c def div(x,y): c=x/y print x,"/",y,"=",c def mod(x,y): c=x%y print x,"%",y,"=",c if C==6: def f(n): if n==1: print n return n else: print n,"*", return n*f(n-1) n=input("enter your no here: ") print f(n) if C==1: a=input("Enter your first no here: ") b=input("Enter your second no here: ") add(a,b) elif C==2: a=input("Enter your first no here: ") b=input("Enter your second no here: ") sub(a,b) elif C==3: a=input("Enter your first no here: ") b=input("Enter your second no here: ") mul(a,b) elif C==4: a=input("Enter your first no here: ") b=input("Enter your second no here: ") div(a,b) elif C==5: a=input("Enter your first no here: ") b=input("Enter your second no here: ") mod(a,b)
[edit] palindrome
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def palindrome(word): if first(word)==last(word): word = middle(word) n=len(word) if n<2: print "palindrome" else: return palindrome(word) else: print "not palindrome" word=raw_input("Enter the string:") palindrome(word)
[edit] sum of all digits
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