{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Algoritmusok Python nyelven\n", "\n", "## 1. Előadás, Bevezetés a programozásba és a Python nyelvbe.\n", "\n", "### 2020. február 13." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Technikai információk\n", "\n", "### Diák elérhetősége:\n", "[damasdigabor.web.elte.hu/teaching](https://damasdigabor.web.elte.hu/teaching)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Oktatók\n", "Előadás: Damásdi Gábor \n", " - Iroda: Déli 3.508\n", " - Fogadó óra: Csütörtök 10:00-12:00 \n", " \n", "Gyakorlat: Csanády Bálint \n", " - http://web.cs.elte.hu/~csbalint/oktatas.html\n", " - Iroda: Déli 3.604\n", "\n", "Gyakorlat: Varga Bálint \n", " - Iroda: Déli 3.605\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Előadás időpontja: 14:00-15:30\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tantárgy célja\n", "\n", "- **Matematikusok számára hasznos programozási tudás átadása**\n", "- Programozás általános folyamatának gyakorlása\n", "- Egy programozási nyelv (Python) alapjainak elsajátítása\n", "- Matematikusoknak hasznos programozási könyvtárak megismerése\n", "- Matematikai algoritmusok implementálása\n", "\n", "- Alapozás későbbi órákhoz(Algoritmusok tervezése és elemzése, Adatbányászat, Deep learning)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tematika\n", "Három fő témakör lesz:\n", " - Python alapjai\n", " - Hasznos könyvtárak\n", " - Matematikai algoritmusok" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tananyag\n", "Az előadás és a gyakorlat anyaga mindig elérhető lesz a honlapon az óra kezdete előtt. [damasdigabor.web.elte.hu/teaching](https://damasdigabor.web.elte.hu/teaching)\n", "#### Források\n", "- [Ács Judit anyaga](https://github.com/bmeaut/python_nlp_2018_spring)\n", "- [SciPy tananyag](https://scipy-lectures.org/index.html)\n", "- [A Python nyelv hivatalos honlapja](https://www.python.org/)\n", "- Sok egyéb\n", "\n", "#### Tutorialok\n", " - [Runestone Academy](https://runestone.academy/runestone/books/published/thinkcspy/index.html)\n", " - [RealPython](https://realpython.com/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Gyakorlat" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Követelmények\n", "- A gyakorlat elvégzése\n", "- Két beadandó feladat elkészítése \n", "- A második beadandó feladat bemutatása (viszgaidőszakban)\n", "- Mindkét feladat osztályozva lesz 1-től 5-ig. \n", "- A végső jegy, A és B osztályzat esetén: " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def vegsojegy(a,b):\n", " if a==1 or b==1:\n", " return 1\n", " if (a+b)%2==0:\n", " return (a+b)/2\n", " else:\n", " if b>a:\n", " return (a+b+1)/2\n", " else:\n", " return (a+b-1)/2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tehát a két jegy átlaga, és ha az nem egész, akkor a második beadandó jegye dönt. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kérdések?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Az általunk használt programozási környezet\n", "\n", "### A programozás sokszínűsége\n", "- Python\n", "- Anaconda\n", "- Jupyter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter\n", "\n", "\n", "- Jupyter - Egy web applikáció melyben olyan dokumentumokat hozhatunk létre, melyek élő kódot, képleteket, grafikonokat tartalmaznak. \n", "- A Jupyter fájlok kiterjesztése `.ipynb`\n", "- de konvertálható sok féle formátumba (HTML, PDF, LateX ...)\n", "- A tartalom cellákba van rendezve. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cella típusok\n", "\n", "\n", "1. kód cella (Python/R/Lua/... kód) \n", "2. szöveg cella\n", "3. markdown cella: Markdown által formatált szöveg" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Kód cella" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n" ] } ], "source": [ "print(\"Hello world\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Az utolsó parancs visszatérési értéke kiíródik. (Általában)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 3\n", "3 + 4" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Ez akár egy több értékből álló \"tuple\" is lehet. (Ahogy sok mindenre, a \"tuple\" szóra sem találtam jó fordítást. Talán \"többes\"?) " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5, 7, 'hello world')" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 3, 3 + 4, \"hello \" + \"world\"" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Markdown cella\n", "\n", "**Ez itt félkövér**\n", "\n", "*Ez meg dőlt*\n", "\n", "| Ez | meg itt |\n", "| --- | --- |\n", "| egy | táblázat |\n", "\n", "Még a Latex is működik:\n", "\n", "$$\n", " \\frac{1}{n}\\sin x= \\frac{sinx}{n}= \\frac{sixn}{n}= six\\frac{n}{n}=six=6\n", "$$\n", "\n" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Ez meg csak egy unalmas szöveges cella" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "\n", "# Jupyter használata\n", "\n", "## Parancs mód és szerkesztési mód\n", "\n", "1. Parancs mód: utasítások végrehajtása a cellákon, a tartalmuk megváltoztatása nélkül. \n", " - A kijelölt cellák kékek\n", "2. Szerkesztési mód: Egy adott cella tartalmának módosítása. \n", " - A kijelölt cella zöld színű" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Váltás a módok között\n", "\n", "1. Esc: Szerkesztési -> Parancs\n", "2. Enter vagy dupla klikk: Parancs -> Szerkesztési" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Cella futtatása szerkesztési módban\n", "\n", "1. Ctrl + Enter: cella futtatása\n", "2. Shift + Enter: cella futtatása és ugrás a következőre\n", "3. Alt + Enter: cella futtatása és új cella beszúrása" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hasznos shortcutok parancs módban\n", "- enter: cella szerkesztése\n", "- a/b : cella beszúrása a kijelölt cella alá/fölé (az above/below alapján)\n", "- m/y : cella típusának váltása: Markdown/Kód\n", "- dd : cella törlése" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2+2" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Cella mágia (cell magic)\n", "\n", "Speciális parancsok, amik módosítják a cella működését." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wall time: 101 ms\n" ] } ], "source": [ "%%time\n", "\n", "for x in range(1000000):\n", " pass" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "59.1 ns ± 4.99 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n" ] } ], "source": [ "%%timeit\n", "\n", "x = 2" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting hello.py\n" ] } ], "source": [ "%%writefile hello.py\n", "\n", "print(\"Hello world\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n" ] } ], "source": [ "!python hello.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Az elérhető mágiák listája:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "application/json": { "cell": { "!": "OSMagics", "HTML": "Other", "SVG": "Other", "bash": "Other", "capture": "ExecutionMagics", "cmd": "Other", "debug": "ExecutionMagics", "file": "Other", "html": "DisplayMagics", "javascript": "DisplayMagics", "js": "DisplayMagics", "latex": "DisplayMagics", "markdown": "DisplayMagics", "perl": "Other", "prun": "ExecutionMagics", "pypy": "Other", "python": "Other", "python2": "Other", "python3": "Other", "ruby": "Other", "script": "ScriptMagics", "sh": "Other", "svg": "DisplayMagics", "sx": "OSMagics", "system": "OSMagics", "time": "ExecutionMagics", "timeit": "ExecutionMagics", "writefile": "OSMagics" }, "line": { "alias": "OSMagics", "alias_magic": "BasicMagics", "autoawait": "AsyncMagics", "autocall": "AutoMagics", "automagic": "AutoMagics", "autosave": "KernelMagics", "bookmark": "OSMagics", "cd": "OSMagics", "clear": "KernelMagics", "cls": "KernelMagics", "colors": "BasicMagics", "conda": "PackagingMagics", "config": "ConfigMagics", "connect_info": "KernelMagics", "copy": "Other", "ddir": "Other", "debug": "ExecutionMagics", "dhist": "OSMagics", "dirs": "OSMagics", "doctest_mode": "BasicMagics", "echo": "Other", "ed": "Other", "edit": "KernelMagics", "env": "OSMagics", "gui": "BasicMagics", "hist": "Other", "history": "HistoryMagics", "killbgscripts": "ScriptMagics", "ldir": "Other", "less": "KernelMagics", "load": "CodeMagics", "load_ext": "ExtensionMagics", "loadpy": "CodeMagics", "logoff": "LoggingMagics", "logon": "LoggingMagics", "logstart": "LoggingMagics", "logstate": "LoggingMagics", "logstop": "LoggingMagics", "ls": "Other", "lsmagic": "BasicMagics", "macro": "ExecutionMagics", "magic": "BasicMagics", "matplotlib": "PylabMagics", "mkdir": "Other", "more": "KernelMagics", "notebook": "BasicMagics", "page": "BasicMagics", "pastebin": "CodeMagics", "pdb": "ExecutionMagics", "pdef": "NamespaceMagics", "pdoc": "NamespaceMagics", "pfile": "NamespaceMagics", "pinfo": "NamespaceMagics", "pinfo2": "NamespaceMagics", "pip": "PackagingMagics", "popd": "OSMagics", "pprint": "BasicMagics", "precision": "BasicMagics", "prun": "ExecutionMagics", "psearch": "NamespaceMagics", "psource": "NamespaceMagics", "pushd": "OSMagics", "pwd": "OSMagics", "pycat": "OSMagics", "pylab": "PylabMagics", "qtconsole": "KernelMagics", "quickref": "BasicMagics", "recall": "HistoryMagics", "rehashx": "OSMagics", "reload_ext": "ExtensionMagics", "ren": "Other", "rep": "Other", "rerun": "HistoryMagics", "reset": "NamespaceMagics", "reset_selective": "NamespaceMagics", "rmdir": "Other", "run": "ExecutionMagics", "save": "CodeMagics", "sc": "OSMagics", "set_env": "OSMagics", "store": "StoreMagics", "sx": "OSMagics", "system": "OSMagics", "tb": "ExecutionMagics", "time": "ExecutionMagics", "timeit": "ExecutionMagics", "unalias": "OSMagics", "unload_ext": "ExtensionMagics", "who": "NamespaceMagics", "who_ls": "NamespaceMagics", "whos": "NamespaceMagics", "xdel": "NamespaceMagics", "xmode": "BasicMagics" } }, "text/plain": [ "Available line magics:\n", "%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %conda %config %connect_info %copy %ddir %debug %dhist %dirs %doctest_mode %echo %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %macro %magic %matplotlib %mkdir %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %ren %rep %rerun %reset %reset_selective %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode\n", "\n", "Available cell magics:\n", "%%! %%HTML %%SVG %%bash %%capture %%cmd %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile\n", "\n", "Automagic is ON, % prefix IS NOT needed for line magics." ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%lsmagic" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Welcome to Python 3.7's help utility!\n", "\n", "If this is your first time using Python, you should definitely check out\n", "the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.\n", "\n", "Enter the name of any module, keyword, or topic to get help on writing\n", "Python programs and using Python modules. To quit this help utility and\n", "return to the interpreter, just type \"quit\".\n", "\n", "To get a list of available modules, keywords, symbols, or topics, type\n", "\"modules\", \"keywords\", \"symbols\", or \"topics\". Each module also comes\n", "with a one-line summary of what it does; to list the modules whose name\n", "or summary contain a given string such as \"spam\", type \"modules spam\".\n", "\n", "help> quit\n", "\n", "You are now leaving help and returning to the Python interpreter.\n", "If you want to ask for help on a particular object directly from the\n", "interpreter, you can type \"help(object)\". Executing \"help('string')\"\n", "has the same effect as typing a particular string at the help> prompt.\n" ] } ], "source": [ "help()\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Mi történik a háttérben\n", "\n", "- minden notebook rendelkezik egy saját _Kernel_ -el (Python interpreter)\n", " - a kernel megszakítható vagy újraindítható a menüből (interrupt/restart) \n", " - **mindig** futtasd a `Kernel -> Restart & Run All` parancsot mielőtt beadnád a házifeladatot/beadandót, hogy megbizonyosodj róla, hogy minden rendben működik\n", "- minden cella egy közös namespace-ben él. \n", "- a cellák tetszőleges sorrendben futtathatóak \n", "- ha újra megnyitunk egy notebookot akkor alapvetően az inputok és az outputok maradnak meg. Az objektumok nem!" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Ez fut először\n" ] } ], "source": [ "print(\"Ez fut először\")" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Aztán meg ez. Figyeld a számot bal oldalt.\n" ] } ], "source": [ "print(\"Aztán meg ez. Figyeld a számot bal oldalt.\")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "a=2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`a` mutasson a 2 értékre." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`a` még mindig a 2-re mutat" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "## A cellák ki és bemenete később is elérhető. " ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "42" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Utolsó előtti output:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'first'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"first\"" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'second'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"second\"" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'first'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "__" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'second'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "__" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Utolsó előtti előtti:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'second'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "___" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Az n. output is elérhető a `_output_count` változón keresztül. Ez csak akkor definiált ha az n. cellának volt kimenete.\n", "\n", "Itt egy módszer az összes elérhető output listázására. (A kódot majd később megérted)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "['_3',\n", " '_4',\n", " '_5',\n", " '_10',\n", " '_15',\n", " '_16',\n", " '_17',\n", " '_18',\n", " '_19',\n", " '_20',\n", " '_21',\n", " '_22']" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(filter(lambda x: x.startswith('_') and \n", " x[1:].isdigit(), globals()))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "## A bemenet hasonlóan elérhető\n", "\n", "Előző input:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "\"list(filter(lambda x: x.startswith('_') and \\n x[1:].isdigit(), globals()))\"" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_i" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "N. input:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "'print(\"Hello world\")'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_i2" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# A Python programozási nyelv" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## A Python története\n", "\n", "\n", "- A Python egy holland programozó hobbi projektjeként indult. (Guido van Rossum)\n", "- Python 1.0 1994\n", "- Python 2.0 2000\n", " - garbage collector\n", " - Unicode támogatás\n", "- Python 3.0 2008\n", " - nem kompatibilis a korábbi verziókkal!! \n", "- Python2 End-of-Life (EOL): January 1, 2020 \n", " - Ezért mi is csak a 3-al foglalkozunk\n", " - Frissítsétek a SAGE-t!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "slideshow": { "slide_type": "slide" } }, "source": [ "## Python közösség és fejlesztés\n", "\n", "- Python Software Foundation nonprofit szervezet (Delaware, US)\n", "- egy erős közösség alakult ki, akik aktívan részt vesznek a fejlesztésben\n", "- nagy standard library\n", "- nagyon nagy third-party modul rendszer: PyPI (Python Package Index)\n", "- pip installer (pip = pip installs packages)\n", "\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "import wikipedia" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['London',\n", " 'City of London',\n", " 'London, Ontario',\n", " 'London Underground',\n", " 'Greater London',\n", " 'Wimbledon, London',\n", " 'London boroughs',\n", " 'University College London',\n", " 'Jack London',\n", " 'The London Gazette']" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "wikipedia.search(\"London\")" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "import antigravity" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python felhasználása\n", " - Web és Internet \n", " - Tudományos számítások \n", " - Tanítás" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# A Python általános tulajdonságai" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interpretált és fordított (compiled) nyelvek. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![interpreted](https://runestone.academy/runestone/books/published/thinkcspy/_images/interpret.png)\n", "![compiled](https://runestone.academy/runestone/books/published/thinkcspy/_images/compile.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Valójában sok nyelv használ vegyes stratégiát, így a python is. Mi főleg interpretált nyelvként fogjuk használni.\n", "###### Interpretált\n", " - gyors programírás\n", " - könnyű hibajavítás\n", " - általában lassabb\n", " - kód és program nincs szétválasztva" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Whitespaces\n", "\n", "- zárójelek helyett indentáció van és befolyásolja a program futását \n", "- nincsenek pontosvesszők " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n páros\n" ] } ], "source": [ "n = 12\n", "if n % 2 == 0:\n", " print(\"n páros\")\n", "else:\n", " print(\"n páratlan\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dinamikus típuskezelés \n", "\n", "- Típusellenőrzés futásidőben történik és nem fordítási időben." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "\n", "n = 2\n", "print(type(n))\n", "\n", "n = 2.1\n", "print(type(n))\n", "\n", "n = \"foo\"\n", "print(type(n))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Értékadás (Assignment)\n", "\n", "Kicsit más mint a legtöbb nyelvben:\n", "\n", "- C++-ban `i = 2` kb azt jelenti, hogy a típussal rendelkező i változó megkapja a 2 érték másolatát.\n", "- Python `i = 2` kb azt jelenti hogy az i név kap egy referenciát egy egy numerikus objektumhoz, aminek az értéke 2. \n", "\n", "- mindig a jobb oldal értékelődik ki először, majd pedig a bal oldali név kap egy referenciát a jobb oldali értékhez\n", "\n", "Az `id` függvény visszaadja az objektum egyedi azonosító számát. (Miért lehet gond az id használatából?)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140733682196912\n", "140733682196944\n" ] } ], "source": [ "i = 2\n", "print(id(i))\n", "\n", "i = 3\n", "print(id(i))" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2715208153648\n", "True\n", "False\n", "False\n" ] } ], "source": [ "i = \"elte\"\n", "print(id(i))\n", "\n", "s = i\n", "print(id(s) == id(i))\n", "\n", "old_id = id(s)\n", "s += \"matek\"\n", "print(id(s) == id(i))\n", "print(old_id == id(s))" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "a = 2\n", "b = a\n", "print(id(a) == id(b))\n", "a += 1\n", "print(id(a) == id(b))" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a=25\n", "b=25\n", "a is b" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a=257\n", "b=257\n", "a is b" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "25 is 25" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "300 is 300" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Egyszerű utasítások" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## if, elif, else" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "N pozitív\n" ] } ], "source": [ "n = int(input())\n", "#n = 12\n", "\n", "if n < 0:\n", " print(\"abrakadara\")\n", " print(\"N negatív\")\n", "elif n > 0:\n", " print(\"N pozitív\")\n", "else:\n", " print(\"N se nem negatív se nem pozitív\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Feltételes kifejezések\n", "\n", "- egysoros `if` utasítások is vannak \n", "- Az operátorok sorrendje viszont különbözik a C nyelvben megszokottaktól. C-ben így nézne ki a kód:\n", "\n", "~~~C\n", "int x = -2;\n", "int abs_x = x>=0 ? x : -x;\n", "~~~\n", "- Csak nagyon rövid kódok esetén ajánlott. \n", "\n", "Pythonban:\n", "\n", "` if else `" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "n = -2\n", "abs_n = n if n >= 0 else -n\n", "print(abs_n)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Listák\n", "\n", "- leggyakrabban használt beépített adatszerkezet\n", "- operációk: indexelés, hossz, hozzáfűzés\n", "- részletesen szó lesz róla később " ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [] # empty list\n", "l.append(2)\n", "l.append(2)\n", "l.append(\"foo\")\n", "\n", "len(l), l\n", "type(l)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "(5, [2, 'bar', 'foo', -1, True])" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l[1] = \"bar\"\n", "l.extend([-1, True])\n", "len(l), l" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## for, range\n", "\n", "### lista iterálása" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "foo\n", "foo\n", "bar\n", "bar\n" ] } ], "source": [ "for e in [\"foo\", \"bar\"]:\n", " print(e)\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Az egészek egy intervallumán való iterálás\n", "\n", "Így nézne ki C++-ban:\n", "~~~C++\n", "for (int i=0; i<5; i++)\n", " cout << i << endl;\n", "~~~\n", "\n", "A `range` mindig 0-val kezdődik!" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Megadhatjuk a kezdőértéket:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(2, 5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Megadhatjuk a növekedés értékét is. Ekkor viszont kötelező megadni a kezdőértéket is. " ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "for i in range(0, 10, 2):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## while" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] }, { "data": { "text/plain": [ "5" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i = 0\n", "while i < 5:\n", " print(i)\n", " i += 1\n", "i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nincs `do...while` Pythonban." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## break és continue\n", "\n", "- `break`: ha korábban ki akarunk lépni egy ciklusból\n", "- `continue`: ha korábban szeretnénk a következő ciklus futásra lépni" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "5\n", "7\n", "9\n" ] } ], "source": [ "for i in range(10):\n", " if i % 2 == 0:\n", " continue\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(10):\n", " if i > 4:\n", " break\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Függvények\n", "\n", "Fontos, hogy ezek nem matematikai függvények. Például nem csak a bemenettől függ a függvényérték. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Függvény definíció\n", "\n", "Függvényeket a `def` kulcsszó segítségévek használhatunk:" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "én egy nagyon okos függvény vagyok\n" ] } ], "source": [ "def foo():\n", " print(\"én egy nagyon okos függvény vagyok\")\n", " \n", "foo()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Függvény argumentumok, paraméterek \n", "\n", "1. pozíció szerinti (positional)\n", "2. kulcsszavas (named or keyword arguments)\n", "\n", "Először a pozíció szerintieket kell írni aztán a kulcsszavasokat" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arg1 1\n", "arg2 2\n", "arg3 asdfs\n" ] } ], "source": [ "def foo(arg1, arg2, arg3):\n", " print(\"arg1 \", arg1)\n", " print(\"arg2 \", arg2)\n", " print(\"arg3 \", arg3)\n", " \n", "foo(1, 2, \"asdfs\")" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n" ] } ], "source": [ "import this" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "import random\n", "def make_maze(w = 16, h = 8):\n", " vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]\n", " ver = [[\"| \"] * w + ['|'] for _ in range(h)] + [[]]\n", " hor = [[\"+--\"] * w + ['+'] for _ in range(h + 1)]\n", " \n", " def walk(x, y):\n", " vis[y][x] = 1\n", " \n", " d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]\n", " random.shuffle(d)\n", " for (xx, yy) in d:\n", " if vis[yy][xx]: continue\n", " if xx == x: hor[max(y, yy)][x] = \"+ \"\n", " if yy == y: ver[y][max(x, xx)] = \" \"\n", " walk(xx, yy)\n", " \n", " walk(random.randrange(w), random.randrange(h))\n", " \n", " s = \"\"\n", " for (a, b) in zip(hor, ver):\n", " s += ''.join(a + ['\\n'] + b + ['\\n'])\n", " return s " ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n", "| | | |\n", "+ + +--+--+ +--+--+ +--+ +--+--+--+ +--+ +\n", "| | | | | | | | | | |\n", "+--+ + + + + + + + +--+--+--+ + +--+ +\n", "| | | | | | | | | | |\n", "+ +--+ + +--+--+--+--+ + +--+ + +--+ + +\n", "| | | | | | | | |\n", "+ + +--+--+--+--+ + + +--+ +--+--+ +--+ +\n", "| | | | | | | | | |\n", "+ + + + +--+ + + + +--+ +--+--+--+ +--+\n", "| | | | | | | | | | |\n", "+--+--+--+ + +--+ + + + +--+ + +--+--+ +\n", "| | | | | | | |\n", "+ +--+--+--+--+--+--+ + +--+ + +--+--+--+--+\n", "| | | |\n", "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n", "\n", "\n" ] } ], "source": [ "\n", "print(make_maze())" ] }, { "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.4" } }, "nbformat": 4, "nbformat_minor": 2 }