{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Algoritmusok Python nyelven\n", "\n", "## 3. Előadás, egyszerű adattípusok, adatszerkezetek folytatás.\n", "\n", "### 2020. február 7." ] }, { "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", "\n", "Óra kezdés: 14:00" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python\n", " - Indentálás, nem kell pontosvessző\n", " - Dinamikus típusok\n", " - Értékadásnál először a jobb oldal kiértékelődik, majd a bal oldalon lévő nevet hozzárendeljük az eredményhez.\n", " - Mutable vs immutable\n", " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### tuple\n", "\n", "- a tuple egy immutable sorozat" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = () # empty tuple\n", "print(type(t), len(t))\n", "\n", "t = ([1, 2, 3], \"foo\")\n", "type(t), len(t)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "indexelés azonos a listákkal" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t[1], t[-1]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "a tuple immutable referenciákat tartalmaz, de, a benne lévő objektum lehet mutable" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = ([1, 2, 3], \"foo\")\n", "#t[0]= \"bar\" # this raises a TypeError" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "for e in t:\n", " print(id(e))\n", " \n", "print(\"\\nMegváltoztatjuk t[0] egy elemét\\n\")\n", "t[0][1] = 11\n", "\n", "for e in t:\n", " print(id(e))\n", "\n", "print(\"\\n\", t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Mire jó a tuple, ha kevesebbet tud mint a lista?\n", " - gyorsabb\n", " - segít a biztonságos kód írásban. \n", " - néha szükség van arra, hogy egy objektum immutable legyen. Pl a most következő dictionaryk kulcsai csak imutable objektumok lehetnek " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Mit kapunk?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print([1+2,1+2])\n", "print([1+2])\n", "print(\"[1+2,1+2]\")\n", "print(\"[1+2]\")\n", "print((1+2,1+2))\n", "print((1+2))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### dictionary\n", "- beépített szótár típus (map)\n", "- kulcsokat képez le értékekre\n", "\n", "(Valójáőban ez sokkal inkább hasonlít a matematikai függvény fogalomhoz, mint a python függvényei.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {} # üres szótár, ekvivalens: d = dict()\n", "d[\"apple\"] = 12\n", "d[\"plum\"] = 2\n", "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "másik megadás" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {\"apple\": 12, \"plum\": 2}\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "muveletek={'+':lambda x,y:x+y,'-':lambda x,y:x-y,'*':lambda x,y:x*y,'/':lambda x,y:x/y }\n", "def muvelet(a,b,operator):\n", " return muveletek[operator](a,b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "muvelet(3,4,\"/\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### kulcs törlése" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "del d[\"apple\"]\n", "d" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### dictionary bejárása\n", "\n", "- a kulcsok és az értékek külön és együtt is bejárhatóak \n", "- kulcsok iterálása" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {\"apple\": 12, \"plum\": 2}\n", "for key in d.keys():\n", " print(key, d[key])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "értékek iterálása" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for value in d.values():\n", " print(value)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "közös iterálás" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for key, value in d.items():\n", " print(key, value)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Mi történik a háttérben?\n", "\n", "- a háttérben egy *hash table* jön létre\n", " - ennek az a lényege, hogy minden kulcshoz hozzárendelünk egy hash értéket, ami egyenlő objektumoknál azonos és az objektumok helyett a hash értéket hasonlítjuk össze. Így gyorsabb lesz a rendszer, mert egy olyan adatstruktúrát alkalmazhatunk, amin ritkán kell változtatni. \n", " - ezért a kulcsok nem lehetnek és nem tartalmazhatnak mutable objektumokat \n", " - de lehetnek különböző tipusú kulcsok" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {}\n", "d[1] = \"a\" # numeric types are immutable\n", "d[3+2j] = \"b\"\n", "d[\"c\"] = 1.0\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hash(1), hash(1000), hash((100,100,1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#hash([21,1])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- a tuple típus immutable" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d[(\"apple\", 1)] = -2\n", "d" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- de a list mutable" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# d[[\"apple\", 1]] = 12 # raises TypeError" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "### Q. Lehetnek-e ezek dictionary kulcsok?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "key1 = (2, (3, 4))\n", "key2 = (2, [], (3, 4))\n", "\n", "d = {}\n", "#d[key1] = 1\n", "#d[key2] = 2\n", "d" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Függvények újra. `args` és `kwargs`\n", "\n", "- mind a pozíciós és a kulcsszavas argumentumok is összegyűjthetőek a `*` és `**` operátorokkal\n", "- a pozíciós argumentumok tuplebe kerülnek" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def arbitrary_positional_f(*args):\n", " print(type(args))\n", " for arg in args:\n", " print(arg)\n", " \n", "arbitrary_positional_f(1, 2, -1)\n", "# arbitrary_positional_f(1, 2, arg=-1) # raises TypeError" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- kulcsszavas argumentumok egy dictionarybe kerülnek" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def arbitrary_keyword_f(**kwargs):\n", " print(type(kwargs))\n", " for argname, value in kwargs.items():\n", " print(argname, value)\n", " \n", "arbitrary_keyword_f(arg1=1, arg2=12)\n", "# arbitrary_keyword_f(12, arg=12) # TypeError" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- általában mindkettőt begyűjtjük " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def arbitrary_arg_f(*args, **kwargs):\n", " if args:\n", " print(\"Pozíció szerinti\")\n", " for arg in args:\n", " print(arg)\n", " else:\n", " print(\"Nincs pozíció szerinti\")\n", " if kwargs:\n", " print(\"Kulcsszavas\")\n", " for argname, value in kwargs.items():\n", " print(argname, value)\n", " else:\n", " print(\"Nincs kulcsszavas\")\n", " \n", "arbitrary_arg_f()\n", "arbitrary_arg_f(12, -2, param1=\"foo\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def arbitrary_arg_f(pos_arg,def_arg=\"default\",*args, **kwargs):\n", " print(pos_arg,def_arg)\n", " if args:\n", " print(\"Pozíció szerinti\")\n", " for arg in args:\n", " print(arg)\n", " else:\n", " print(\"Nincs pozíció szerinti\")\n", " if kwargs:\n", " print(\"Kulcsszavas\")\n", " for argname, value in kwargs.items():\n", " print(argname, value)\n", " else:\n", " print(\"Nincs kulcsszavas\")\n", " print(\"\\n\") \n", "arbitrary_arg_f(1,2)\n", "arbitrary_arg_f(12, param1=\"foo\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# set\n", "\n", "- egyedi, hash-elhető elemek (így ebben sem nem lehet mutable)\n", "- alapvető halmazműveletek használhatóak" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = set()\n", "s.add(2)\n", "s.add(3)\n", "s.add(2)\n", "s" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = {2, 3, 2} #d={'a':2}\n", "type(s), s" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#s = {[1,2]}" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### deleting elements" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s.add(2)\n", "s.remove(2)\n", "# s.remove(2) # KeyErrort kapunk mert már töröltük\n", "s.discard(2) # töröl, ha benne van, különben semmit sem csinál" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## set operációk\n", "\n", " - két féle jelölés van rájuk\n", " 1. függvények\n", " 2. operátorok" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s1 = {1, 2, 3, 4, 5}\n", "s2 = {2, 5, 6, 7}\n", "\n", "s1 & s2 # s1.intersection(s2) vagy s2.intersection(s1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s1 | s2 # s1.union(s2) vagy s2.union(s1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s1 - s2, s2 - s1 # s1.difference(s2), s2.difference(s1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- ezek az operációk egy új `set`-tel térnek vissza. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s3 = s1 & s2\n", "type(s3), id(s3) == id(s1), id(s3) == id(s2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### `issubset` és `issuperset`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s1 < s2, s1.issubset(s2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "{1, 2} < s1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "s1.issuperset({1, 6})" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## hasznos tulajdonságok \n", "\n", "- egy set létrehozásával megszüntethetjük a duplikációkat egy listában" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = [1, 2, 3, -1, 1, 2, 1, 0]\n", "uniq = set(l)\n", "uniq" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- set-ek és dictionary-k O(1) időben keresnek. (gyorsak)\n", "- listák O(n) időben keresnek." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"-\".join([\"Ez\",\"egy\",\"módszer\",\"stringek\",\"összefűzésére\"])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "random.choice([\"egy\",\"két\",\"há\"]) # egy lista véletlenszerű eleme" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "letters = \"abcdef\"\n", "word_len = [1, 2, 3, 4, 5]\n", "N = 10000\n", "samples = []\n", "\n", "for i in range(N):\n", " word = []\n", " for j in range(random.choice(word_len)):\n", " word.append(random.choice(letters))\n", " samples.append(\"\".join(word))\n", " \n", "samples = list(samples)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "word = []\n", "for j in range(random.choice(word_len)):\n", " word.append(random.choice(letters))\n", "word = \"\".join(word)\n", "print(word)\n", "word in samples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### list lookup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%timeit\n", "\n", "word = []\n", "for j in range(random.choice(word_len)):\n", " word.append(random.choice(letters))\n", "word = \"\".join(word)\n", "word in samples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### set lookup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "samples_set = set(samples)\n", "len(samples_set), len(samples)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%timeit\n", "\n", "word = []\n", "for j in range(random.choice(word_len)):\n", " word.append(random.choice(letters))\n", "word = \"\".join(word)\n", "word in samples_set" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Stringek\n", "\n", "- A stringek **immutable** sorozatok, melyek Unicode karaterekből állnak" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pelda=\"ez egy string\"\n", "single = 'ab\\'c'\n", "double = \"ab\\\"c\"\n", "multiline = \"\"\"\n", "sdfajfklasj;\n", "sdfsdfs\n", "sdfsdf\n", "\"\"\"\n", "single == double" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- mivel immutable, nem lehet megváltoztatni!!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"abcdefg\"\n", "s[3:7]\n", "# s[1] = \"c\" # TypeError" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- minden string operáció új függvényt hoz létre" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(id(s))\n", "s = s + \"def\"\n", "id(s), s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- a stringekre is elérhető a legtöbb függvény, amit a listák tudnak.\n", " - pl: indexelés" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"abcdefghijkl\"\n", "s[::2], \"x\" in s," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"ábc\"\n", "print(type(s))\n", "\n", "with open(\"file.txt\", \"w\") as f:\n", " f.write(s)\n", " f.write(\"\\n\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open(\"file.txt\") as f:\n", " text = f.read().strip()\n", " \n", "print(text)\n", "type(text)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## String operációk\n", "\n", "- rengeteg függvény elérhető" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "\"abC\".upper(), \"ABC\".lower(), \"abc\".title()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"\\tabc \\n\"\n", "print(\"\" + s + \"\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "s.strip()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s.rstrip()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s.lstrip()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"abca\".strip(\"a\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Mivel minden függvény visszatér egy új stringgel, egymás után fűzhetőek." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\" abcd abc\".strip().rstrip(\"c\").lstrip(\"ab\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Eldöntendő kérédsek" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"abc\".startswith(\"ab\"), \"abc\".endswith(\"cd\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"abc\".istitle(), \"Abc\".istitle()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "\" \\t\\n\".isspace()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"989\".isdigit(), \"1.5\".isdigit()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### split és join" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"the quick brown fox jumps over the lazy dog\"\n", "words = s.split()\n", "words" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"R.E.M.\"\n", "s.split(\".\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "\n", "\"-\".join(words)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Példa: Egy wikipedia oldal szó frekvenciája" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " # Ez csak akkor működik, ha a wikipedia csomag már telepítve van. Később részletesebben lesz szó arról,\n", " # hogy hogyan lehet telepíteni. Alapvetően a pip install wikipedia parancsot\n", " # kell kiadni windowson az anaconda promptban, linuxon pedig a terminálban. \n", " \n", " import wikipedia\n", " article = wikipedia.page(\"Hungary\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text=article.content" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "words = text.split()\n", "len(words), len(set(words))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "word_freq = {}\n", "for word in words:\n", " if word not in word_freq:\n", " word_freq[word] = 1\n", " else:\n", " word_freq[word] += 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "for word, freq in sorted(word_freq.items(), key=lambda x: -x[1])[:40]:\n", " print(word, freq)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List comprehension\n", "\n", "- Rövidités a foor loop leggyakoribb használatára, hogy gyorsan tudjunk listákat létrehozni" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = []\n", "for i in range(10):\n", " l.append(2*i+1)\n", "l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Egy soros megfelelő:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = [2*i+1 for i in range(10)]\n", "l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Az általános formula \n", "\n", "~~~\n", "[ for in ]\n", "~~~" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "even = [n*n for n in range(20) if n % 2 == 0]\n", "even" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ami azzal ekvivalens, hogy" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "even = []\n", "for n in range(20):\n", " if n % 2 == 0:\n", " even.append(n)\n", "even" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "egy feltételt is megadhatunk, hogy szűrjük az elemeket:\n", "\n", "~~~\n", "[ for in if ]\n", "~~~\n", "- mivel itt szűrésre használjuk az `if` részt, nincs `else` ág\n", "\n", "- viszont a kezdeti kifejezésben használhatunk esetszétválasztást:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = [1, 0, -2, 3, -1, -5, 0]\n", "\n", "signum_l = [int(n / abs(n)) if n != 0 else 0 for n in l]\n", "signum_l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ez persze nem a list comprehension extrája, hanem csak annyi, hogy ez is egy értelmes kifejezés:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = -3.2\n", "int(n / abs(n)) if n != 0 else 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Több listán is végigfuthatunk:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l1 = [1, 2, 3]\n", "l2 = [4, 5, 6]\n", "\n", "[(i, j) for i in l1 for j in l2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "[(i, j) for j in l2 for i in l1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Egymásba is ágyazhatjuk őket:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "matrix = [\n", " [1, 2, 3],\n", " [5, 6, 7]\n", "]\n", "\n", "[[e*e for e in row] for row in matrix]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set és dictionary comprehension\n", "\n", "Minden analóg módon működik:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fruit_list = [\"apple\", \"plum\", \"apple\", \"pear\"]\n", "\n", "fruits = {fruit.title() for fruit in fruit_list}\n", "\n", "type(fruits), len(fruits), fruits" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "word_list = [\"apple\", \"plum\", \"pear\", \"apple\", \"apple\"]\n", "word_length = {word: len(word) for word in word_list}\n", "type(word_length), len(word_length), word_length" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "word_list = [\"apple\", \"plum\", \"pear\", \"avocado\"]\n", "first_letters = {word[0]: word for word in word_list}\n", "first_letters" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in word_length.keys():\n", " if len(i)%2==0:\n", " print(i)\n", " #del word_length[i]\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "{a:word_length[a] for a in word_length.keys() if len(a)%2==1}" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Mutable alapértelmezett argumentumok\n", "\n", "- csak óvatosan!!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def insert_value(value, l=[]):\n", " l.append(value)\n", " print(l)\n", " \n", "l1 = []\n", "insert_value(12, l1)\n", "l2 = []\n", "insert_value(14, l2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "insert_value(-1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "insert_value(-3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- legjobb ha messzire elkerüljük" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Egy lehetséges megoldás:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def insert_value(value, l=None):\n", " if l is None:\n", " l = []\n", " l.append(value)\n", " return l\n", "\n", "l = insert_value(2)\n", "l" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "insert_value(12)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Lambda kifejezések\n", "\n", "- névtelen függvények\n", "- lehet paramétere\n", "- egy kifejezést számít ki" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = [-1, 0, -10, 2, 3]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Rendezzünk például abszolút érték szerint. A beépített `sorted` függvény nem elég." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "De megadhatjuk, hogy milyen `key` kulcsot használjon:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for e in sorted(l, key=lambda x: abs(x)):\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Bármilyen függvényt használhatunk" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "for e in sorted(l, key=abs):\n", " print(e)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(lambda x,y: 1/(x**3+y+1))(1,2)" ] } ], "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 }