diff --git a/online_judges/ransom_note/ransom_note_solution.ipynb b/online_judges/ransom_note/ransom_note_solution.ipynb index 345e0a0..258e59b 100644 --- a/online_judges/ransom_note/ransom_note_solution.ipynb +++ b/online_judges/ransom_note/ransom_note_solution.ipynb @@ -88,24 +88,22 @@ }, "outputs": [], "source": [ + "from collections import Counter\n", + "\n", + "\n", "class Solution(object):\n", "\n", " def match_note_to_magazine(self, ransom_note, magazine):\n", - " if ransom_note is None or magazine is None:\n", - " raise TypeError('ransom_note or magazine cannot be None')\n", - " seen_chars = {}\n", - " for char in magazine:\n", - " if char in seen_chars:\n", - " seen_chars[char] += 1\n", - " else:\n", - " seen_chars[char] = 1\n", - " for char in ransom_note:\n", - " try:\n", - " seen_chars[char] -= 1\n", - " except KeyError:\n", - " return False\n", - " if seen_chars[char] < 0:\n", + " if not isinstance(ransom_note, str) or not isinstance(magazine, str):\n", + " raise TypeError('Invalid arguments provided.')\n", + " \n", + " characters_in_magazine = Counter(magazine)\n", + " characters_in_note = Counter(ransom_note)\n", + " \n", + " for character, count in characters_in_note.items():\n", + " if count > characters_in_magazine.get(character, 0):\n", " return False\n", + " \n", " return True" ] },