Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Enter number of terms: 4\n",
- "The Fibonacci sequence consisting of 4 elements is:\n",
- "0\n",
- "1\n",
- "1\n",
- "2\n"
- ]
- }
- ],
- "source": [
- "n = int(input(\"Enter number of terms: \"))\n",
- "def fib(n):\n",
- " if(n <= 1):\n",
- " return n\n",
- " else:\n",
- " return(fib(n-1) + fib(n-2))\n",
- "\n",
- "print(\"The Fibonacci sequence consisting of\",n ,\"elements is:\")\n",
- "for i in range(n):\n",
- " print (fib(i))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#Alternative Approach (by using while loop)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Enter the number of elements of the series 6\n",
- "Fibonacci series including 6 elements is:\n",
- "0\n",
- "1\n",
- "1\n",
- "2\n",
- "3\n",
- "5\n"
- ]
- }
- ],
- "source": [
- "x=int(input(\"Enter the number of elements of the series \"))\n",
- "a=0\n",
- "b=1\n",
- "i=2\n",
- "if x<= 0:\n",
- "\tprint (\"Enter a positive integer: \")\n",
- "elif x== 1:\n",
- "\tprint (\"Fibonacci series including one element is\",x,\":\")\n",
- "\tprint (a)\n",
- "else:\n",
- "\tprint (\"Fibonacci series including\",x,\"elements is:\")\n",
- "\tprint (a)\n",
- "\tprint (b)\n",
- "\t\n",
- "\twhile i<x:\n",
- "\t\tc=a+b\n",
- "\t\tprint (c)\n",
- "\t\ta=b\n",
- "\t\tb=c\n",
- "\t\ti=i+1"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "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.7.3"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement