Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "ce0feff9-8e09-4427-b78c-c608946a9a9b", "metadata": {}, "source": [ "### Q18\n", "Find the maximum total from top to bottom of the triangle below:" ] }, { "cell_type": "code", "execution_count": 1, "id": "9c425f99-9f70-4a2b-aac0-e06f46b9706e", "metadata": {}, "outputs": [], "source": [ "num_triangle_string = \"\"\"\n", "75\n", "95 64\n", "17 47 82\n", "18 35 87 10\n", "20 04 82 47 65\n", "19 01 23 75 03 34\n", "88 02 77 73 07 63 67\n", "99 65 04 28 06 16 70 92\n", "41 41 26 56 83 40 80 70 33\n", "41 48 72 33 47 32 37 16 94 29\n", "53 71 44 65 25 43 91 52 97 51 14\n", "70 11 33 28 77 73 17 78 39 68 17 57\n", "91 71 52 38 17 14 91 43 58 50 27 29 48\n", "63 66 04 68 89 53 67 30 73 16 69 87 40 31\n", "04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n", "\"\"\"" ] }, { "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 35 µs, sys: 5 µs, total: 40 µs\n", "Wall time: 40.8 µs\n" ] }, { "data": { "text/plain": [ "1074" ] }, "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 Q17
Next Notebook:
Project Euler Q19
Loading