mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
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:
parent
ba3fb473b1
commit
f4b8ecd30c
|
@ -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"
|
||||
]
|
||||
},
|
||||
|
|
Loading…
Reference in New Issue
Block a user