Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "a469358e-2f57-4bd6-9c8d-c59f3d77920b", "metadata": {}, "source": [ "### Q42\n", "Using [q42_data.txt](/notebook/raw/q42_data.txt), a 16K text file containing nearly two-thousand common English words, how many are triangle words?" ] }, { "cell_type": "code", "execution_count": 1, "id": "32720930-c7b6-4882-87f6-945b254594fc", "metadata": {}, "outputs": [], "source": [ "words_string = open(\"q42_data.txt\",\"r\").read()" ] }, { "cell_type": "code", "execution_count": 2, "id": "820c6f59-d5d1-4f67-a379-b41d8bb337ac", "metadata": {}, "outputs": [], "source": [ "def words_string_to_list(words_string):\n", " return words_string.replace('\"',\"\").split(\",\")\n", "\n", "def char_score(char):\n", " return ord(char.upper())-64\n", "\n", "def is_triangle_num(n):\n", " a = int((n*2)**0.5)\n", " return a*(a+1) == n*2\n", "\n", "def count_triangle_word(words_string):\n", " words_list = words_string_to_list(words_string)\n", " result = 0\n", " for word in words_list:\n", " if is_triangle_num(sum(char_score(c) for c in word)):\n", " result += 1\n", " return result" ] }, { "cell_type": "code", "execution_count": 3, "id": "1b65c5f8-02b2-4db4-95ab-9343702ded41", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 1.58 ms, sys: 0 ns, total: 1.58 ms\n", "Wall time: 1.58 ms\n" ] }, { "data": { "text/plain": [ "162" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "count_triangle_word(words_string)" ] }, { "cell_type": "code", "execution_count": null, "id": "3ff0b0de-a9d5-4a15-8a67-2f1f75ff175d", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }
Previous Notebook:
Project Euler Q41
Next Notebook:
Project Euler Q43
Loading