{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Fibonacci numbers\n", "-----------------\n", "\n", "The Fibonacci numbers is the number of the following sequence $$f_0 = f_1 = 1 \\qquad f_{n+2} = f_{n+1} + f_n.$$ We will see two loops to generate Fibonacci numbers:\n", "- the first one builds the list of Fibonacci numbers\n", "- the second one only computes two consecutive terms $(f_n, f_{n+1})$\n", "\n", "Depending on the problem you are considering you might want loop of the first kind or of the second one." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]\n" ] } ], "source": [ "# this loop generates the list of Fibonacci numbers\n", "L = [1, 1]\n", "for i in range(10):\n", " L.append(L[-1] + L[-2])\n", "print(L)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "144\n" ] } ], "source": [ "# this loop go through the fibonacci numbers\n", "# (below we only print the last term)\n", "f0 = f1 = 1\n", "for i in range(10):\n", " tmp = f0 + f1\n", " f0 = f1\n", " f1 = tmp\n", "print(f1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.5.2" } }, "nbformat": 4, "nbformat_minor": 1 }