add problem 42
This commit is contained in:
parent
cb12d06321
commit
8b74c1cf57
|
@ -0,0 +1,104 @@
|
|||
{
|
||||
"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)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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
|
||||
}
|
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue