eulerbooks/notebooks/problem0022.ipynb

97 lines
2.6 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "266f39d0",
"metadata": {},
"source": [
"# [Names Scores](https://projecteuler.net/problem=22)\n",
"\n",
"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))"
]
},
{
"cell_type": "markdown",
"id": "7c61f808",
"metadata": {},
"source": [
"#### Copyright (C) 2025 filifa\n",
"\n",
"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)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 9.5",
"language": "sage",
"name": "sagemath"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}