In: Computer Science
Problem 1 (Ransom Note Problem) in python
A kidnapper kidnaps you and writes a ransom note. He does not write it by hand to avoid having his hand writing being recognized, so he uses a magazine to create a ransom note. We need to find out, given the ransom string and magazine string, is it possible to create a given ransom note. The kidnapper can use individual characters of words.
Here is how your program should work to simulate the ransom problem:
Example: If the magazine string is “programming problems are weird”
If the ransom note is: “no see” your program should print true as all the characters in “no see” exist in the magazine string.
If the ransom note is “no show” your program should print false as not all the characters in “no show” exist in the magazine string as you can see the character ‘h’ does not exist.
Program
def ransom_note(magazine, ransom):
hash_words = {}
# Create the hash tabled with the words on
the
# magazine and put the number of occurrence in
the value.
for m_word in magazine:
if
hash_words.get(m_word) != None:
if (hash_words[m_word] > 0):
hash_words[m_word] += 1
else:
hash_words[m_word] = 1
# Check if exist the word in the hash
table
for r_word in ransom:
if
hash_words.get(r_word) is None or hash_words[r_word] == 0:
return False
else:
hash_words[r_word] -= 1
return True
m = "programming problems are weird"
n = "are"
magazine_list = m.split(' ')
ransom_list = n.split(' ')
answer = ransom_note(magazine_list, ransom_list)
if answer:
print ("True")
else:
print ("False")
Output
True
Screenshot