Homework Solution

While Loops and Functions

Problems to be Submitted (18 points)

  1. (4 points)

    print "Start entering words:"
    previous = []
    word = raw_input()
    while word not in previous:
        previous.append(word)
        word = raw_input()
    print "You already entered " + word + "."
    print "You listed", len(previous), "distinct words."
    
    (click to see it run live)

  2. (4 points)

    def acronym(phrase):
        a = ''
        for word in phrase.split():
            a += word[0]
        return a.upper()
    
    (click to see it run live)

    Or, for those who like to use list comprehensions,

    def acronym(phrase):
        return ''.join([word[0] for word in phrase.split()]).upper()
    


  3. (10 points)

    def isSubstring(pattern, original):
      for j in range(1+len(original)-len(pattern)):     # possible start within original
        isMatch = True                                  # let's be optimistic	
        for k in range(len(pattern)):                   # offset from start
          if pattern[k] != original[j+k]:
            isMatch = False                             # found mismatch for this alignment    
        if isMatch:
          return True                                   # we found a perfect match
    
      return False      # if we get this far, no match was found	
    
    (click to see it run live)

Extra Credit

  1. (2 points)

    def pairSum(data, goal):
      for a in range(len(data)-1):
        for b in range(a+1, len(data)):
          if data[a] + data[b] == goal:
            return True
      return False  
    

Last modified: Thursday, 05 October 2017