donnemartin/interactive-coding-challenges · error · TypeError

s or t cannot be None

Error message

s or t cannot be None

What it means

find_diff (find the difference between two strings where t is a permutation of s plus one extra char) raises TypeError when either s or t is None. The counting-dict logic iterates both strings, so None would fail with a less clear error; the guard fails fast with an explicit message. The algorithm itself assumes both inputs are strings of the same alphabet.

Solutions

  1. Pass both strings, using '' for the legitimately empty case
  2. Default missing inputs to empty strings at the boundary: s = s or ''
  3. Add tests covering the None contract so callers know it is intentionally rejected

Example fix

// before
sol.find_diff(s, t)  # t is None
// after
sol.find_diff(s if s is not None else '', t if t is not None else '')
Defensive patterns

Strategy: validation

Validate before calling

s = s or ''
t = t or ''
sol.find_diff(s, t)

Type guard

def is_str(x):
    return isinstance(x, str)

Try / catch

try:
    sol.find_diff(s, t)
except TypeError as e:
    if 's or t cannot be None' in str(e):
        raise ValueError('both strings are required') from e
    raise

Prevention

When it happens

Trigger: Calling Solution().find_diff(None, 'abc') or find_diff('abc', None) or both None; passing t loaded from a file/stream that hit EOF and returned None.

Common situations: String pairs read from paired files or API fields where one side is missing; notebook variables not yet assigned before the cell runs; optional request parameters forwarded without defaults.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/f73f3b45f8a3e047. Report an issue: GitHub.

Appendix: source

Thrown at online_judges/str_diff/str_diff_solution.ipynb:90

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "\n",
    "    def find_diff(self, s, t):\n",
    "        if s is None or t is None:\n",
    "            raise TypeError('s or t cannot be None')\n",
    "        seen = {}\n",
    "        for char in s:\n",
    "            if char in seen:\n",
    "                seen[char] += 1\n",
    "            else:\n",
    "                seen[char] = 1\n",
    "        for char in t:\n",
    "            try:\n",
    "                seen[char] -= 1\n",
    "            except KeyError:\n",
    "                return char\n",
    "            if seen[char] < 0:\n",
    "                return char\n",
    "        return None"
   ]
  },
  {
   "cell_type": "markdown",

View on GitHub (pinned to 358f2cc604)