donnemartin/interactive-coding-challenges · error · TypeError
ransom_note or magazine cannot be None
Error message
ransom_note or magazine cannot be None
What it means
Raised by Solution.match_note_to_magazine when either ransom_note or magazine is None. The method builds a character-count dict from the magazine and then consumes it against the note, so both must be actual strings; the combined guard rejects None for either argument with a clear message.
Source
Thrown at online_judges/ransom_note/ransom_note_solution.ipynb:93
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"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",
" return False\n",
" return True"
]
},
{
"cell_type": "markdown",View on GitHub (pinned to 358f2cc604)
Solutions
- Default both arguments to '' at the call site: match_note_to_magazine(note or '', mag or '').
- Fix the extraction step to raise or return '' instead of None.
- Wrap the call in try/except TypeError for robust batch processing.
Example fix
# before Solution().match_note_to_magazine(note, mag) # note may be None # after Solution().match_note_to_magazine(note or '', mag or '')
Defensive patterns
Strategy: type-guard
Validate before calling
note = note or '' magazine = magazine or '' can_match = Solution().match_note_to_magazine(note, magazine)
Type guard
def is_str(x):
return isinstance(x, str) Try / catch
try:
Solution().match_note_to_magazine(note, magazine)
except TypeError as e:
if 'cannot be None' in str(e):
can_match = False
else:
raise Prevention
- Make text extraction return '' on failure instead of None.
- Coalesce both string arguments with 'or ""' before calling.
When it happens
Trigger: Calling match_note_to_magazine(None, 'abc'), match_note_to_magazine('abc', None), or with both None.
Common situations: Text-extraction steps (OCR, file read, HTTP fetch) that return None on failure and are passed straight in; optional fields from a form or API payload.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/2da4c3f85f4bfa3d.
Report an issue: GitHub.