eulerbooks/notebooks/problem0042.ipynb

115 lines
2.6 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "67a42435",
"metadata": {},
"source": [
"# [Coded Triangle Numbers](https://projecteuler.net/problem=42)"
]
},
{
"cell_type": "markdown",
"id": "94f69404",
"metadata": {},
"source": [
"First we read in the words:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "8d7380ba",
"metadata": {},
"outputs": [],
"source": [
"with open(\"txt/0042_words.txt\") as f:\n",
" words = {w.strip('\"') for w in f.read().split(\",\")}"
]
},
{
"cell_type": "markdown",
"id": "0a73cc47",
"metadata": {},
"source": [
"We'll also write a simple function for testing if a word is a \"triangle word\". We'll make use of SageMath's built-in function for testing if a number is triangular."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "313a760f",
"metadata": {},
"outputs": [],
"source": [
"def is_triangle_word(word):\n",
" value = sum(ord(c) - ord('A') + 1 for c in word)\n",
" return is_triangular_number(value)"
]
},
{
"cell_type": "markdown",
"id": "ba53d2b1",
"metadata": {},
"source": [
"(It's not difficult to apply the quadratic formula to write our own test for [triangular numbers](https://en.wikipedia.org/wiki/Triangular_number).)\n",
"\n",
"Now we just test each word."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "14a9ea9a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"162"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"triangle_words = {w for w in words if is_triangle_word(w)}\n",
"len(triangle_words)"
]
},
{
"cell_type": "markdown",
"id": "02bf08bf",
"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
}