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

Chapter 10 edit

CH 10 - Solution 1 edit

CH 10 - Solution 1.1 edit

>>> import calendar
>>> year = calendar.calendar(2008)
>>> print year
                                  2008

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                      1  2
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       3  4  5  6  7  8  9
14 15 16 17 18 19 20      11 12 13 14 15 16 17      10 11 12 13 14 15 16
21 22 23 24 25 26 27      18 19 20 21 22 23 24      17 18 19 20 21 22 23
28 29 30 31               25 26 27 28 29            24 25 26 27 28 29 30
                                                    31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                1  2  3  4                         1
 7  8  9 10 11 12 13       5  6  7  8  9 10 11       2  3  4  5  6  7  8
14 15 16 17 18 19 20      12 13 14 15 16 17 18       9 10 11 12 13 14 15
21 22 23 24 25 26 27      19 20 21 22 23 24 25      16 17 18 19 20 21 22
28 29 30                  26 27 28 29 30 31         23 24 25 26 27 28 29
                                                    30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3       1  2  3  4  5  6  7
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       8  9 10 11 12 13 14
14 15 16 17 18 19 20      11 12 13 14 15 16 17      15 16 17 18 19 20 21
21 22 23 24 25 26 27      18 19 20 21 22 23 24      22 23 24 25 26 27 28
28 29 30 31               25 26 27 28 29 30 31      29 30

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2       1  2  3  4  5  6  7
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       8  9 10 11 12 13 14
13 14 15 16 17 18 19      10 11 12 13 14 15 16      15 16 17 18 19 20 21
20 21 22 23 24 25 26      17 18 19 20 21 22 23      22 23 24 25 26 27 28
27 28 29 30 31            24 25 26 27 28 29 30      29 30 31

>>>


CH 10 - Solution 1.2 edit

isleap(year) - Return 1 for leap years, 0 for non-leap years.


>>> from calendar import *
>>> isleap(2008)
True
>>> isleap(2009)
False
>>>

CH 10 - Solution 2 edit

CH 10 - Solution 2.1 edit

 python C:\Python26\Lib\pydoc.py -p 7464 

CH 10 - Solution 2.2 edit

There are 35 functions in the math module.

CH 10 - Solution 2.3 edit

The floor function finds the greatest integral value less than or equal to x. The ceil function finds the lowest integeral value greater than or equal to x.

CH 10 - Solution 2.4 edit

CH 10 - Solution 2.5 edit

The two data constants in the math module are: 'e' and 'pi'.

CH 10 - Solution 3 edit

"""
Interface summary:

        import copy

        x = copy.copy(y)        # make a shallow copy of y
        x = copy.deepcopy(y)    # make a deep copy of y

For module specific errors, copy.Error is raised.

The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances).

- A shallow copy constructs a new compound object and then (to the
  extent possible) inserts *the same objects* into it that the
  original contains.

- A deep copy constructs a new compound object and then, recursively,
  inserts *copies* into it of the objects found in the original."""

deepcopy would have come handy in exercises you didn't have to solve regarding object reference, thus no answer is excpected here.

CH 10 - Solution 4 edit

CH 10 - Solution 5 edit

CH 10 - Solution 6 edit

Namespaces are one honking great idea -- let's do more of those!

CH 10 - Solution 7 edit

CH 10 - Solution 8 edit

def matrix_mult(m1, m2):

  """
     >>> matrix_mult([[1, 2], [3,  4]], [[5, 6], [7, 8]])
     [[19, 22], [43, 50]]
     >>> matrix_mult([[1, 2, 3], [4,  5, 6]], [[7, 8], [9, 1], [2, 3]])
     [[31, 19], [85, 55]]
     >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]])
     [[39, 54, 69], [13, 23, 33], [14, 19, 24]]
   """
  
  qr = len(m1)
  qc = len(m2[0])
  NewMtx = []
  for row in range(qr):
      newRow = []
      for column in range(qc):
          newRow.append(row_times_column(m1, row, m2, column))
      NewMtx.append(newRow)
  return NewMtx

return NewMtx

     qr = len(m1)
  qc = len(m2[0])
  NewMtx = []
  for row in range(qr):
      newRow = []
      for column in range(qc):
          newRow.append(row_times_column(m1, row, m2, column))
      NewMtx.append(newRow)

CH 10 - Solution 9 edit

CH 10 - Solution 10 edit

def myreplace(old, new, s):
    """
    Replace all occurences of old with new in the string s.

      >>> myreplace(',', ';', 'this, that, and, some, other, thing')
      'this; that; and; some; other; thing'
      >>> myreplace(' ', '**', 'Words will now be separated by stars.')
      'Words**will**now**be**separated**by**stars.'
      
    """
    old_removed = s.split(old)
    new_added = new.join(old_removed)
    return new_added
# Shorter version
#    new_added = new.join(s.split(old))

CH 10 - Solution 11 edit

def cleanword(word):
    """
      >>> cleanword('what?')
      'what'
      >>> cleanword('"now!"')
      'now'
      >>> cleanword('?+="word!,@$()"')
      'word'
    """
    cleaned_word = ''
    for i in range(len(word)):
        char = word[i]
        if char.isalpha():
            cleaned_word += char
    return cleaned_word
    

def has_dashdash(s):
    """
      >>> has_dashdash('distance--but')
      True
      >>> has_dashdash('several')
      False
      >>> has_dashdash('critters')
      False
      >>> has_dashdash('spoke--fancy')
      True
      >>> has_dashdash('yo-yo')
      False
    """
    return s.find('--') != -1


def extract_words(s):
    """
      >>> extract_words('Now is the time!  "Now", is the time? Yes, now.')
      ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
      >>> extract_words('she tried to curtsey as she spoke--fancy')
      ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
    """
    if has_dashdash(s):
        s = myreplace('--', ' ', s) #using myreplace function from Q. 10
    words_punc = s.split()
    cleanlist = []
    for word in words_punc:
        cleanedword = cleanword(word).lower()
        cleanlist.append(cleanedword)
    return cleanlist
        
        
def wordcount(word, wordlist):
    """
      >>> wordcount('now', ['now', 'is', 'time', 'is', 'now', 'is', 'is'])
      ['now', 2]
      >>> wordcount('is', ['now', 'is', 'time', 'is', 'now', 'is', 'the', 'is'])
      ['is', 4]
      >>> wordcount('time', ['now', 'is', 'time', 'is', 'now', 'is', 'is'])
      ['time', 1]
      >>> wordcount('frog', ['now', 'is', 'time', 'is', 'now', 'is', 'is'])
      ['frog', 0]
    """

    return [word, wordlist.count(word)]


def wordset(wordlist):
    """
      >>> wordset(['now', 'is', 'time', 'is', 'now', 'is', 'is'])
      ['is', 'now', 'time']
      >>> wordset(['I', 'a', 'a', 'is', 'a', 'is', 'I', 'am'])
      ['I', 'a', 'am', 'is']
      >>> wordset(['or', 'a', 'am', 'is', 'are', 'be', 'but', 'am'])
      ['a', 'am', 'are', 'be', 'but', 'is', 'or']
    """

    for word in wordlist:
        count = wordcount(word, wordlist)[1]
        if count > 1:
            for a in range(count - 1):
                wordlist.remove(word)
    wordlist.sort()
    return wordlist
            

def longestword(wordset):
    """
      >>> longestword(['a', 'apple', 'pear', 'grape'])
      5
      >>> longestword(['a', 'am', 'I', 'be'])
      2
      >>> longestword(['this', 'that', 'supercalifragilisticexpialidocious'])
      34
    """
    longest = 0
    for word in wordset:
        length = len(word)
        if length > longest:
            longest = length
    return longest


if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 10 - Solution 12 edit

#sort_fruits.py

source = open('unsorted_fruits.txt', 'r')
fruits = source.readlines()
source.close()
fruits.sort()
newfile = open('sorted_fruits.txt', 'w')
newfile.writelines(fruits)
newfile.close()

CH 10 - Solution 13 edit

CH 10 - Solution 14 edit

#mean.py

from sys import argv

nums = argv[1:]

for i, value in enumerate(nums):
    nums[i] = float(value)

mean = sum(nums) / len(nums)

print mean

CH 10 - Solution 15 edit

#median.py

from sys import argv
nums = argv[1:]

for i, value in enumerate(nums):
    nums[i] = float(value)

nums.sort()
size = len(nums)
middle = size / 2

if size % 2 == 0:
    median = (nums[middle - 1] + nums[middle]) / 2
else:
    median = nums[middle]

if median == float(int(median)):
    median = int(median)

print median

CH 10 - Solution 16 edit

#
# countletters.py
#

def display(i):
    if i == 10: return 'LF'
    if i == 13: return 'CR'
    if i == 32: return 'SPACE'
    return chr(i)

from sys import argv

filename = argv[1]

infile = open(filename, 'r')
text = infile.read()
infile.close()

counts = 128 * [0]

for letter in text:
    counts[ord(letter)] += 1

filenamesplit = filename.split('.') # splits 'name.txt' -> ['name', 'txt']
count_file = filenamesplit[0] + '_counts.dat' # 'name' -> 'name_counts.dat'

outfile = open(count_file, 'w')
outfile.write("%-12s%s\n" % ("Character", "Count"))
outfile.write("=================\n")

for i in range(len(counts)):
    if counts[i]:
        outfile.write("%-12s%d\n" % (display(i), counts[i]))

outfile.close()