How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Solutions

The following section contains answers to the exercises in the Book.

Chapter 1
Exercise 1:

Exercise 2:

Exercise 3:

def main:

nowtime = int(raw_input("what time now: "))

t = int(raw_input("Input the hour go off your wanted: "))

time = t + nowtime

days = time//24

hour = time % 24

print "The hour will go off after days: ", days, " at hour: ", hour

pass

if __name__ == '__main__': main

Chapter 3
Solution 4 def cat_n_times(s, n): string=s print string*n

CH 6 - Solution 1
$ cat ch0601.py

print 'produces', '\n', 'this', '\n', 'output'

$ python ch0601.py

produces

this

output

CH 6 - Solution 2
$ cat ch0602.py

def sqrt(n): approx = n/2.0 better = (approx + n/approx)/2.0 while better != approx: print better approx = better better = (approx + n/approx)/2.0 return approx print sqrt(25)

$ python ch0602.py

7.25 5.34913793103 5.01139410653 5.00001295305 5.00000000002 5.0

CH 6 - Solution 3
def print_multiples(n, high): i = 1 while i <= high: print n*i, '\t', i += 1 print def print_mult_table(high): i = 1 while i <= high: print_multiples(i, high) i += 1 if __name__ == "__main__": high = input("Enter a number : ") print_mult_table(high)

CH 6 - Solution 6 Part 1
What will num_digits(0) return?

CH 6 - Solution 6 Part 2
Modify it to return 1 for this case.

CH 6 - Solution 6 Part 3
Why does a call to num_digits(-24) result in an infinite loop (hint: -1/10 evaluates to -1)?

The loop will end when n = 0, and per above -1/10 == -1, causing an infinite loop.

CH 7 - Question 1
Modify: so that Ouack and Quack are spelled correctly.

CH 7 - Notes regarding Question 1
Note that  is a substitution of traversal, for example:

is substituted by:

CH 7 - Question 2
Encapsulate:

in a function named, and generalize it so that it accepts the string and the letter as arguments.

CH 7 - Solution 2
Tracing the program:

CH 7 - Solution 4
Re: the versions of is_lower:


 * 1) this is the fastest!!!

CH 7 - Question 5
Create a file named stringtools.py and put the following in it:

Add a function body to reverse to make the doctests pass.

CH 7 - Solution 5
Now inorder to make the doctest pass we need to enclose our ouput in a string. Here we use a placeholder string: lastoutput = "".

Second, we remove redundant code:

per:

by using negative indices, such as:

to:

CH 8 - Solution 4
Not fully complete but...

CH 12 Solution 3
The word "alice" occurs 386 times (not including 12 occurences of "alice's")

CH 12 Solution 4
The longest 'word' in the list is "bread-and-butter" with 16 characters. This can be found by adding the following code to the alice_words.py program: Slightly altering this we can find the longest unhyphenated word, "disappointment", which has 14 characters.

Chapter 13

 * 1) date:3-5-2015
 * 2) author:m.khodakarami@ut.ac.ir
 * 3) this program will reverse the lines of any given file

for line in reversed(open('test.txt').readlines): print(line.rstrip)