Wednesday, March 2, 2011

Find if the words in a bunch of magazines contains the words you need for a ransom note

Let's say you are writing a ransom note
or maybe you are aspiring to be the next uni bomber.

You have magazines laying around and you need to know if they have all the words that you need for your secret note.

Here's the code. Is it correct?
"""
magazine1 = ['a', 'b', ...]
magazine2 = ['a', 'b', ...]

note = ['a', 'b' ]


e.g. note = ['please', 'please']
magazines = [['please', 'yes'], ['no']]
"""

def hasAllWords(note, magazines):
  mastercount = {}
  for mag in magazines:
    for word in mag:
      if word in mastercount:
        mastercount[word]= mastercount[word] + 1
      else:
        mastercount[word]=1


  for word in note:
    if word not in masterlist:
      return false
    mastercount[word] = mastercount[word] - 1
    if mastercount[word] == 0:
      mastercount.remove(word)
  return true

No comments: