Update ransom note solution to be more Pythonic

collections.Counter allows us to simplify the solution. Is it *too* Python specific?
This commit is contained in:
Kevin London 2017-06-21 10:58:48 -07:00 committed by GitHub
parent ba3fb473b1
commit f4b8ecd30c

View File

@ -88,24 +88,22 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"from collections import Counter\n",
"\n",
"\n",
"class Solution(object):\n", "class Solution(object):\n",
"\n", "\n",
" def match_note_to_magazine(self, ransom_note, magazine):\n", " def match_note_to_magazine(self, ransom_note, magazine):\n",
" if ransom_note is None or magazine is None:\n", " if not isinstance(ransom_note, str) or not isinstance(magazine, str):\n",
" raise TypeError('ransom_note or magazine cannot be None')\n", " raise TypeError('Invalid arguments provided.')\n",
" seen_chars = {}\n", " \n",
" for char in magazine:\n", " characters_in_magazine = Counter(magazine)\n",
" if char in seen_chars:\n", " characters_in_note = Counter(ransom_note)\n",
" seen_chars[char] += 1\n", " \n",
" else:\n", " for character, count in characters_in_note.items():\n",
" seen_chars[char] = 1\n", " if count > characters_in_magazine.get(character, 0):\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",
" return False\n", " return False\n",
" \n",
" return True" " return True"
] ]
}, },