{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## [Függvények](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)\n", "\n", "### Alapfogalmak\n", "\n", "- A függvény névvel ellátott alprogram, amely a program más részeiből meghívható.\n", "- Függvények használatával a számítási feladatok kisebb egységekre oszthatók. A gyakran használt függvények kódját könyvtárakba rendezhetjük.\n", "- A matematikában egy függvénynek nincsenek mellékhatásai. Egy Python nyelvű függvénynek lehetnek!\n", "\n", "\n", "- Pythonban a függvények \"teljes jogú állampolgárok\":\n", " + Egy változónak értékül adhatunk egy függvényt.\n", " + Függvényeket egymásba lehet ágyazni.\n", " + Egy függvény kaphat paraméterként függvényt ill. adhat eredményül függvényt.\n", " \n", "\n", "- Fontos különbséget tenni egy függvény *definíciója* és *meghívása* között:\n", " + A függvény definíciója megadja, hogy milyen bemenethez milyen kimenet rendelődjön (és milyen mellékhatások hajtódjanak végre). A függvény definíciója a programban általában csak egy helyen szerepel (ha több helyen szerepel, akkor az utolsó definíció lesz az érvényes.)\n", " + A függvény meghívása azt jelenti, hogy egy adott bemenethez kiszámítjuk a hozzárendelt értéket. Egy függvényt a programban többször is meg lehet hívni." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Példa: n-edik gyök függvény definiálása.\n", "def root(x, n=2):\n", " '''Returns the n-th root of x.'''\n", " return x**(1 / n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ha a függvény első utasítása egy sztring, akkor ez lesz a függvény dokumentációs sztringje." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Returns the n-th root of x.'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Dokumentációs sztring (docstring) lekérdezése.\n", "root.__doc__ # \"dunder doc\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# A __doc__ attribútum egy közönséges sztring, tetszés szerint végezhetünk vele műveleteket.\n", "root.__doc__ *= 10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Pythonban a függvényeknek *pozícionális* és *kulcsszó* paraméterei lehetnek.\n", " + Függvénydefiníciókor először a pozícionális majd a kulcsszó paramétereket kell felsorolni.\n", " + A pozícionális paramétereknek nincs alapértelmezett értékük, a kulcsszó paramétereknek van.\n", " + Mindegyik paramétertípusból lehet nulla darab is.\n", "- Függvényhíváskor...\n", " + Az összes pozícionális paraméter értékét meg kell adni, olyan sorrendben, ahogy a definíciónál szerepeltek,\n", " + A kulcsszó paraméterek értékét nem kötelező megadni." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.4142135623730951" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Gyök 2 kiszámítása.\n", "root(2)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.2599210498948732" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Köbgyök 2 kiszámítása.\n", "root(2, n=3)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.2599210498948732" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# A második paramétert nem kell nevesíteni.\n", "root(2, 3)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# Változónak értékül adhatunk függvényt.\n", "f = root" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "function" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(f)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(16, n=4)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# Példa egymásba ágyazásra ill. függvényt visszaadó függvényre.\n", "def f(y):\n", " def g(x):\n", " return x * y\n", " return g" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# f egy \"függvénygyár\"\n", "g2 = f(2) # kétszerező függvény\n", "g3 = f(3) # háromszorozó függvény" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g2(10)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "60" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g3(20)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Gyakorlás" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Prímtesztelés\n", "\n", "Készítsünk függvényt, amely eldönti egy természetes számról, hogy prím-e!" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# 1. változat: függvény nélkül\n", "n = 17\n", "\n", "is_prime = True\n", "for i in range(2, int(n**0.5) + 1):\n", " if n % i == 0:\n", " is_prime = False\n", " break\n", " \n", "print(is_prime and n > 1)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "# 2. változat: függvénnyel\n", "def is_prime(n):\n", " for i in range(2, int(n**0.5) + 1):\n", " if n % i == 0:\n", " return False\n", " return n > 1" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "is_prime(1)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "is_prime(2)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "is_prime(12)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "is_prime(13)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Legnagyobb közös osztó\n", "\n", "Készítsünk függvényt két természetes szám legnagyobb közös osztójának a meghatározására!" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "# 1. változat: függvény nélkül\n", "a = 18\n", "b = 12\n", "\n", "for i in range(min(a, b), 0, -1):\n", " if a % i == 0 and b % i == 0: # i közös osztó?\n", " break\n", " \n", "print(i)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "# 2. változat: függvénnyel\n", "def calc_gcd(a, b):\n", " for i in range(min(a, b), 0, -1):\n", " if a % i == 0 and b % i == 0: # i közös osztó?\n", " return i" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "calc_gcd(12, 18)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "calc_gcd(13, 18)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Másodfokú egyenlet megoldó\n", "\n", "Készítsünk másodfokú egyenlet megoldó függvényt!" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def solve_quadratic(a, b, c):\n", " '''Solve quadratic equation a*x^2 + b*x + c = 0,\n", " and return solutions in a list.'''\n", " \n", " # diszkrimináns kiszámítása\n", " d = b**2 - 4 * a * c\n", "\n", " # elágazás\n", " if d > 0: # 2 megoldás\n", " x1 = (-b + d**0.5) / (2 * a)\n", " x2 = (-b - d**0.5) / (2 * a)\n", " return [x1, x2]\n", " elif d == 0: # 1 megoldás\n", " return [-b / (2 * a)]\n", " else:\n", " return []" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2.0, 1.0]" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solve_quadratic(1, -3, 2)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[-1.0]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solve_quadratic(1, 2, 1)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solve_quadratic(1, 1, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## [Lambda kifejezések](https://docs.python.org/3/reference/expressions.html#lambda)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A lambda kifejezés nem más, mint egysoros, névtelen függvény.\n", "- (A [funkcionális programozás](https://en.wikipedia.org/wiki/Functional_programming) egyéb elemei a Pythonban: [map](https://docs.python.org/3/library/functions.html#map), [filter](https://docs.python.org/3/library/functions.html#filter).)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "142" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Példa lambda kifejezésre.\n", "f = lambda x: x + 42\n", "f(100)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Egynél több bemenet is megengedett.\n", "g = lambda x, y: x + y\n", "g(10, 20)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# ...de akár nulla bemenet is lehet.\n", "h = lambda: 100\n", "h()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda kifejezés alkalmazása rendezésnél" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('körte', 11), ('alma', 22), ('barack', 33)]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Párok listájának rendezése a második elem szerint.\n", "pairs = [('alma', 22), ('körte', 11), ('barack', 33)]\n", "sorted(pairs, key=lambda p: p[1])" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('körte', 11), ('alma', 22), ('barack', 33)]" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Az előző feladat megoldása lambda kifejezés nélkül.\n", "pairs = [('alma', 22), ('körte', 11), ('barack', 33)]\n", "def key_func(p):\n", " return p[1]\n", "sorted(pairs, key=key_func)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['king', 'queen', 'denmark']" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Szótárkulcsok rendezése az értékek szerint csökkenő sorrendbe.\n", "words = {'king': 203, 'denmark': 24, 'queen': 192}\n", "sorted(words, key=lambda k: words[k], reverse=True)" ] } ], "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.11.3" } }, "nbformat": 4, "nbformat_minor": 2 }