Homework Solution

Functions and Exceptions

Problems to be Submitted (20 points)

  1. (5 points)
    def acronym(phrase):
        a = ''
        for word in phrase.split():
            a += word[0]
        return a.upper()
    
    or for those who like to use list comprehensions
    def acronym(phrase):
        return ''.join([word[0] for word in phrase.split()]).upper()
    

  2. (5 points)
    def threshold(dailyGains, goal):
      day = 0
      subtotal = 0.0
      while subtotal < goal and day < len(dailyGains):
        subtotal += dailyGains[day]
        day += 1
      if subtotal < goal:
        day = 0              # goal was unachievable
      return day
    
  3. (5 points)
    def cheerlead(word):
      for letter in word.upper():
        print 'Gimme',
        if letter in 'AEFHILMNORSX':
          print 'an',
        else:
          print 'a ',
        print letter
      print "What's that spell?"
      print word
    
  4. (5 points)
    def sliding(word, num=3):
      if not isinstance(word, str):
        raise TypeError('word must be a string')
      if not isinstance(num, int):
        raise TypeError('num must be an integer')
      if num <= 0:
        raise ValueError('num must be positive')
      if num > len(word):
        raise ValueError('num cannot be greater than the word length')
      for i in range(len(word) + 1 - num):
        print ' ' * i + word[i:i+num]
    

Extra Credit

  1. (2 points)

    def toDecimal(string, base):
      place = 1
      total = 0
      original = string[ : :-1]   # reverse for convenience
      for symbol in original:
        if symbol.isdigit():
          value = int(symbol)
        else:
          value = 10 + ord(symbol) - ord('A')
        total += value * place
        place *= base
      return total
    

Last modified: Wednesday, 03 March 2010