{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 6##\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A function can call other functions. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create function that calculate squares. Call it square. Having just one parameter. \n", " " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create function that calculate sume of squares, using previsou function call it SumofSquares(), \n", "with a parameter def ListValues. \n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Call the fucntion using the follwoing data" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "46" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "listValues=[2,4,1,5]\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is even possible for the function to call itself. \n", "These types of construct are termed as recursive functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a factorial function without recursion:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now the factorial function but using recursion" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def factorial(x):\n", " if x == 1:\n", " return 1\n", " else:\n", " return (x * factorial(x-1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Advantages \n", "* Complex task can be splited into smaller (and less complex) subtasks\n", "* Using recursion in sequence generation is esear that nested iteration\n", "* The code look clean and elegant.\n", "\n", "Disadvantages\n", "* Uses large ammont of memory and time.\n", "* Not easy to undertand logic of the code\n", "* Hard to debug.\n" ] }, { "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.6" } }, "nbformat": 4, "nbformat_minor": 4 }