Homework Solution

Functions

Problems to be Submitted (20 points)

  1. (5 points)
    words = []
    next = raw_input('Start entering words:\n')
    while next not in words:
        words.append(next)
        next = raw_input()
    print 'You already entered ' + next + '.'
    print 'You listed', len(fruits), 'distinct words.'
    

  2. (5 points)
    def sliding(word, num=3):
      for i in range(len(word) + 1 - num):
        print ' ' * i + word[i:i+num]
    
  3. (5 points)

    Here is a version that works if we can assume that the list is non empty, and thus we can legitimately initialize shortSoFar to stringList[0].

    def minLength(stringList):
      shortSoFar = stringList[0]                 # use the first entry
      for entry in stringList[1: ]:              # check rest of the list
        if len(entry) < len(shortSoFar):         # for even shorter lengths
          shortSoFar = entry
      return shortSoFar
    
    Here is a more robust version that works in all cases, returning None when the list is empty.
    def minLength(stringList):
      shortSoFar = None
      for entry in stringList:
        if shortSoFar is None or len(entry) < len(shortSoFar):
          shortSoFar = entry
      return shortSoFar
    
  4. (5 points)
    def greaterIndex(data, value):
      answer = 0
      while answer < len(data) and data[answer] <= value:
        answer += 1
      return answer
    

Extra Credit

  1. (2 points)

    def convertToBase(value, base):
        result = ''
        while value > 0:
            q = value / base
            r = value % base
            result = str(r) + result
            value = q
        return result
    

Last modified: Monday, 22 February 2010