This notebook was prepared by Donne Martin. Source and license info is on GitHub.
Complexity:
class Solution(object):
def match_note_to_magazine(self, ransom_note, magazine):
if ransom_note is None or magazine is None:
raise TypeError('ransom_note or magazine cannot be None')
seen_chars = {}
for char in magazine:
if char in seen_chars:
seen_chars[char] += 1
else:
seen_chars[char] = 1
for char in ransom_note:
try:
seen_chars[char] -= 1
except KeyError:
return False
if seen_chars[char] < 0:
return False
return True
%%writefile test_ransom_note.py
import unittest
class TestRansomNote(unittest.TestCase):
def test_ransom_note(self):
solution = Solution()
self.assertRaises(TypeError, solution.match_note_to_magazine, None, None)
self.assertEqual(solution.match_note_to_magazine('', ''), True)
self.assertEqual(solution.match_note_to_magazine('a', 'b'), False)
self.assertEqual(solution.match_note_to_magazine('aa', 'ab'), False)
self.assertEqual(solution.match_note_to_magazine('aa', 'aab'), True)
print('Success: test_ransom_note')
def main():
test = TestRansomNote()
test.test_ransom_note()
if __name__ == '__main__':
main()
Overwriting test_ransom_note.py
%run -i test_ransom_note.py
Success: test_ransom_note