Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "7f2a5876-649a-4789-b148-c21b83942c06", "metadata": {}, "source": [ "### Q2\n", "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms." ] }, { "cell_type": "code", "execution_count": 1, "id": "5cf6759f-9608-4da1-abe6-f086689bdd0e", "metadata": {}, "outputs": [], "source": [ "def fibonacci(first, second, n_term = False, max_value = False):\n", " result = [first, second]\n", " if not n_term and not max_value:\n", " print(\"At least one of 'n_term','max_value' argument is needed.\")\n", " return\n", " while True:\n", " if n_term and len(result) >= n_term:\n", " break\n", " if max_value and result[-1] > max_value:\n", " result.pop()\n", " break\n", " result.append(result[-1]+result[-2])\n", " return result " ] }, { "cell_type": "code", "execution_count": 2, "id": "dfff5794-6043-4c85-a697-d6e5f92bc261", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 9 µs, sys: 2 µs, total: 11 µs\n", "Wall time: 12.9 µs\n" ] }, { "data": { "text/plain": [ "4613732" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "sum(fibonacci(1,2,max_value=4000000)[1::3])" ] }, { "cell_type": "code", "execution_count": null, "id": "59c68984-9ecc-4626-a6a9-e2cc1592bfc8", "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 Q1
Next Notebook:
Project Euler Q3
Loading