"First, let's read the names into a list. We'll also strip the quotes around each name and sort them."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2f23e8ed",
"metadata": {},
"outputs": [],
"source": [
"with open(\"txt/0022_names.txt\") as f:\n",
" names = f.read().split(',')\n",
" \n",
"for (i, name) in enumerate(names):\n",
" names[i] = name.strip('\"')\n",
" \n",
"names.sort()"
]
},
{
"cell_type": "markdown",
"id": "947bb620",
"metadata": {},
"source": [
"The [`ord` function](https://docs.python.org/3/library/functions.html) returns the [Unicode](https://en.wikipedia.org/wiki/Unicode) code point of the provided character. Conveniently, the code point for `A` is 65, `B` is 66, and so on, so we can just subtract 64 to get an (uppercase) letter's number value. (These code points were chosen to be the same as [ASCII's](https://en.wikipedia.org/wiki/ASCII) for backward compatibility. [Here's a short but informative video on Unicode and UTF-8](https://www.youtube.com/watch?v=MijmeoH9LT4).)\n",
"\n",
"Add up these number values for a name, multiply by the position in the list, and sum up."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9966edb4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"871198282"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def name_score(pos, name):\n",
" return pos * sum(ord(c) - 64 for c in name)\n",
"\n",
"\n",
"sum(name_score(i, name) for (i, name) in enumerate(names, start=1))"
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."