Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "ce0feff9-8e09-4427-b78c-c608946a9a9b", "metadata": {}, "source": [ "### Q67\n", "Find the maximum total from top to bottom in [file](/notebook/raw/q67_data.txt), a 15K text file containing a triangle with one-hundred rows." ] }, { "cell_type": "code", "execution_count": 1, "id": "9c425f99-9f70-4a2b-aac0-e06f46b9706e", "metadata": {}, "outputs": [], "source": [ "num_triangle_string = open(\"q67_data.txt\",\"r\").read()" ] }, { "cell_type": "code", "execution_count": 2, "id": "9b2e4340-8c44-45ce-adeb-44ce64455df4", "metadata": {}, "outputs": [], "source": [ "def num_triangle_string_to_list(num_triangle_string):\n", " return [[int(ele) for ele in line.strip().split(\" \")] for line in num_triangle_string.strip().split(\"\\n\")]\n", "\n", "def vector_add(vector_a,vector_b):\n", " return [vector_a[i]+vector_b[i] for i in range(len(vector_a))]\n", "\n", "def max_path(num_triangle_string):\n", " num_triangle_list = num_triangle_string_to_list(num_triangle_string)\n", " num_list_len = len(num_triangle_list)\n", " if num_list_len == 0:\n", " return 0\n", " if num_list_len == 1:\n", " return num_triangle_list[0][0]\n", " for i in range(num_list_len-2,-1,-1):\n", " sons = num_triangle_list.pop()\n", " max_sons = [sons[j] if sons[j] > sons[j+1] else sons[j+1] for j in range(i+1)]\n", " num_triangle_list[i] = vector_add(num_triangle_list[i],max_sons)\n", " return num_triangle_list[0][0]" ] }, { "cell_type": "code", "execution_count": 3, "id": "58a4d119-c3c1-41e7-b577-9b2a60dc654d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 837 µs, sys: 136 µs, total: 973 µs\n", "Wall time: 975 µs\n" ] }, { "data": { "text/plain": [ "7273" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "max_path(num_triangle_string)" ] }, { "cell_type": "code", "execution_count": null, "id": "b7d67ff3-af1d-4b43-b5e1-321c0b0440b7", "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 Q59
Loading