{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Примеры готовых функций в Python" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "print(8)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from math import sqrt" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.449489742783178" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sqrt(6) + sqrt(9) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Написание собственных функций в Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Напишем код, который будет вычислять факториал от числа $n$ ($n!$):" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "120\n" ] } ], "source": [ "n = 5\n", "f = 1\n", "\n", "for i in range(2, n + 1):\n", " f = f * i\n", " \n", "print(f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Теперь напишем функцию `factorial()`, которая принимает на вход целое число, а возвращает факториал этого числа:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " f = 1\n", " for i in range(2, n + 1):\n", " f = f * i\n", " return f" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "362880" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "factorial(9) " ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "factorial(3) + factorial(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Сравнение `return` vs `print`" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "def say_hello(name):\n", " print(\"Hello,\", name)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alla\n" ] } ], "source": [ "w = say_hello(\"Alla\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "print(w) " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "def say_hello(name):\n", " h = \"Hello, \" + name\n", " print(h)\n", " return h" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alla\n" ] } ], "source": [ "w2 = say_hello(\"Alla\")" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello, Alla'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Ещё немного о функциях" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Напишем функцию, которая будет вычислять биномиальный коэффициент:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C_n^k = \\frac{n!}{k!(n-k)!}\n", "$$" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "def binom_coeff(n, k):\n", " \"\"\"\n", " Calculates binomial coefficient.\n", " Parameters:\n", " n – is an integer\n", " k – is an integer\n", " Returns:\n", " binomial coeff (integer)\n", " \"\"\"\n", " res = factorial(n) // (factorial(k) * factorial(n - k))\n", " return res" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "binom_coeff(6, 2) " ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function binom_coeff in module __main__:\n", "\n", "binom_coeff(n, k)\n", " Calculates binomial coefficient.\n", " Parameters:\n", " n – is an integer\n", " k – is an integer\n", " Returns:\n", " binomial coeff (integer)\n", "\n" ] } ], "source": [ "help(binom_coeff)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "А теперь напишем функцию, которая не только принимает на вход два аргумента, но и возвращает сразу два результата (оба результата в return объединятся в кортеж):" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "def my_power(a, b):\n", " return a ** b, b ** a" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(64, 81)" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_power(4, 3) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Сохраним результаты отдельно (множественное присваивание):" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "x1, x2 = my_power(4, 3) " ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x1" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "81" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Аргументы по умолчанию" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Пользователь обязательно должен подать на вход функции язык приветствия:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def hello(name, lang):\n", " if lang == \"ru\":\n", " print(f\"Здравствуйте, {name}!\")\n", " if lang == \"en\":\n", " print(f\"Hello, {name}!\")\n", " if lang == \"fr\":\n", " print(f\"Bonjours, {name}!\")\n", " return" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alla!\n" ] } ], "source": [ "hello(\"Alla\", \"en\") " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Если пользователь забудет указать язык, по умолчанию будет использоваться английский (`en`):" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "def hello(name, lang = \"en\"):\n", " if lang == \"ru\":\n", " print(f\"Здравствуйте, {name}!\")\n", " if lang == \"en\":\n", " print(f\"Hello, {name}!\")\n", " if lang == \"fr\":\n", " print(f\"Bonjours, {name}!\")\n", " return" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alla!\n" ] } ], "source": [ "hello(\"Alla\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Многие функции и методы в Python имеют значения по умолчанию. Так, метод `.split()` на строках по умолчанию разбивает строку по пробелу:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"a-b-c\".split(\"-\") # задали символ для разбиения" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"a b c\".split() # ничего не задали – используется пробел" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Произвольное число аргументов" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6 7 a [3, 7]\n" ] } ], "source": [ "print(6, 7, \"a\", [3, 7]) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Используем `*`, чтобы функция приняла на вход любое количество аргументов, а потом объединила из в кортеж:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "def my_fun(*args):\n", " m = max(args)\n", " return m" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_fun(9, 5, 0, 5, 2, 1, 11) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda-функции" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "def my_square(x):\n", " return x ** 2" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "36" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_square(6) " ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "sq = lambda x: x ** 2" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "145" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sq(9) + sq(8)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "my_sum = lambda x, y: x + y" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_sum(6, 5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lambda s: s.strip() " ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "L = [0, 2, 7, 5, 4, 3, 2] " ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[7, 5, 4]" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[x for x in L if x > 3] " ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[7, 5, 4]" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(filter(lambda x: x > 3, L)) " ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[5, 4]" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(filter(lambda x: (x > 3) & (x < 6), L))" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 4, 49, 25, 16, 9, 4]" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[x ** 2 for x in L] " ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 4, 49, 25, 16, 9, 4]" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(map(lambda x: x ** 2, L)) " ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.75 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" ] } ], "source": [ "%%timeit\n", "\n", "[x ** 2 for x in L] " ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.14 µs ± 27.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n" ] } ], "source": [ "%%timeit\n", "list(map(lambda x: x ** 2, L)) " ] } ], "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.4" } }, "nbformat": 4, "nbformat_minor": 2 }