{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# Potęgowanie...\n", "a = 2**10\n", "print(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "2**63" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "2**128" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "2**4000" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "a = len(str(2**4000))\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1.0 / 10 == 0.1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "0.1 == 0.10000000000000001" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "# Data types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = [0,1,2,3]\n", "print(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Listy w pythonie są bardzo elastyczne\n", "arr = [1,2,'cos', [10,11,12], 3.14]\n", "print(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = [0,1,2,3]\n", "print(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "len(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wartość której komórki zostanie odczytana?\n", "arr[1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Elementy listy można łatwo nadpisać\n", "arr[2] = 2\n", "arr[2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "arr[1] = 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czy to zadziała?\n", "arr[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wartości których komórek zostaną odczytane?\n", "arr[1:3]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[:3]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[-2:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[-3:-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = [0,1,2,3,4,5,6]\n", "arr[0:5]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[0:5:2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[::2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[::-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Konkatenacja\n", "a=[0,1,2,3]\n", "b=['a','b','c','d']\n", "a+b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dodawanie do listy\n", "a=[10,20,30,40]\n", "a.append(100)\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Usuwanie z listy\n", "a=[10,20,20,30,40]\n", "a.remove(20)\n", "a.pop(3)\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Python ma wiele fajnych funkcji, np.\n", "a = [4, 6, 'd','y', 3 ,6]\n", "'d' in a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a.index('d')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czym się różni tuple od listy? (Poza nawiasami)\n", "a = (1,2,3)\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czytamy tak samo\n", "a[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b = (2,3,4)\n", "\n", "c = a + b\n", "c" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = b + c\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co się teraz stanie?\n", "a[1]=1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "oceny = {'polski': 3.5, \n", " 'matematyka': 5,\n", " 'fizyka': 4, \n", " 'informatyka': 6}\n", "oceny" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Odczytanie wartości dla klucza\n", "oceny['informatyka']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "oceny['wf']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Łatwo można dodać ocenę\n", "oceny['nowy przedmiot'] = 2.0\n", "oceny" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A także nadpisać \n", "oceny['nowy przedmiot'] = 4.0\n", "oceny" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Sets" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Zbiory. Takie jak w matematyce. Jakie są dwie podstawowe włąsności zbiorów? \n", "ulubione_przedmioty = set(['polski', 'muzyka', 'geografia', 'historia'])\n", "ulubione_przedmioty" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czy element należy do zbioru?\n", "'informatyka' in ulubione_przedmioty\n", "#'polski' in ulubione_przedmioty" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Zastosowanie z ifem (data flow będzie dalej)\n", "# UWAGA NA WCIĘCIA\n", "if 'polski' in ulubione_przedmioty:\n", " print('Kocham j. polski!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = set(['a','b','c','d'])\n", "b = set(['c','d','e','f'])\n", "a = a.union(b)\n", "l = list(a)\n", "print(l)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a.intersection(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a.difference(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Jak usunąć duplikaty z listy?\n", "l = [1, 2, 'b', 4, 2, 'b', 'c']\n", "s = set(l)\n", "nl = list(s)\n", "print(nl)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dlaczego nie można tak?\n", "s = set(['a', 'b', 'c'])\n", "pos = s.index('a')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 4\n", "print('asdasdas ' + str(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# łańcuchy znaków...\n", "print('Imię: {}'.format('Wojciech'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from math import pi\n", "print(' Imię: {},\\n Nazwisko: {},\\n PESEL: {},\\n Ulubiona: {}\\n'\n", " .format('Wojciech', 'Jaśkowski', '8212...', pi))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można nadać identyfikator {identyfikator}\n", "# Czy kolejnośc ma w takim razie znaczenie?\n", "from math import pi\n", "print(''' \n", "Imię: {imie},\n", "Nazwisko: {nazw},\n", "PESEL: {pesel},\n", "Ulubiona: {ulub}\n", "'''.format(\n", " nazw='Jaśkowski', \n", " imie='Wojciech', \n", " pesel='8212...', \n", " ulub=pi))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czy da radę to wyświetlić?\n", "print('ęśćńżół')\n", "print('יהוה')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Po łańcuchu znaków można w sumie iterować, więc...\n", "s = 'ala'\n", "print(s[0:2])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czy jest jakaś różnica?\n", "print('ala')\n", "print(\"ala\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ciekawostka\n", "print('ala ma \\' \"kota\"')\n", "print(\"ala ma 'kota'\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Bardzo łatwo można w pythonie dokonywać konwersji między łańcuchem znaków a inną zmienną.\n", "str(12)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "int('12')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "float('12.1')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = 'Python is easy;really?'\n", "text.split()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text.split(';')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wciąż nie fajnie, ale...\n", "import re\n", "re.split(' |;', text)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = ['a','b','c','d']\n", "str(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'; '.join(arr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Flow control" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = ['a', 'b', 'c', 'd']\n", "for a in arr:\n", " print(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(range(0, 4))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(len(arr)):\n", " print(i, arr[i])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# W poprzednich podejściach mieliśmy albo element, albo indeks. \n", "# A można mieć to i to \n", "\n", "#list(enumerate(arr))\n", "\n", "for i, a in enumerate(arr):\n", " print(i, a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = [0,1,2,3]\n", "b = ['a','b','c','d']\n", "n = len(a)\n", "for i in range(n):\n", " print(a[i], b[i])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A co jeżeli chcemy iterować jednocześnie po dwóch listach?\n", "a = [0,1,2,3]\n", "b = ['a','b','c','d']\n", "for x, y in zip(a, b):\n", " print(x, y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(zip(a,b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A po trzech?\n", "c=['ala','ma','kota','!']\n", "zipped = list(zip(a,b,c))\n", "zipped" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Skoro można 'zipować', to można także 'odzipować'\n", "a, b, c = list(zip(*zipped))\n", "print(a)\n", "print(b)\n", "print(c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# If w pythonie jest bardzo prosty (pamiętamy o ':' oraz braku '{ }')\n", "arr = [0,1,2,3]\n", "for a in arr:\n", " if (a % 3 == 0):\n", " print('0 = {} mod 3'.format(a))\n", " elif a % 3 == 1:\n", " print('1 = {} mod 3'.format(a))\n", " else:\n", " print('2 = {} mod 3'.format(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pętla while to też pestka. Jaki tu będzie wynik?\n", "s = 'python'\n", "while s[0] != 'h':\n", " s = s[1:]\n", "print(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# and (nawiasy nie są konieczne)\n", "a = 1\n", "if -1 <= a and (a <= 1):\n", " print('A is in range')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 'and' czasami też nie jest konieczny...\n", "if -1 <= a <= 1:\n", " print('A is in range')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# negacja \n", "a = [1, 2, 3]\n", "if not 4 in a:\n", " print('4 is missing')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# continue, break\n", "a = 2\n", "while (a < 5):\n", " a = a + 1\n", " print(a)\n", " if (a == 3):\n", " break\n", " #continue" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iterating over dictionaries" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co odczytujemy?\n", "# Co z kolejnością?\n", "\n", "d = {'a': 1, \n", " 'b': 2, \n", " 12: 'mama', \n", " 4:23}\n", "\n", "for v in d:\n", " print(str(v) + ' => ' + str(d[v]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A gdybyśmy chcieli mieć klucz i wartość od razu?\n", "\n", "#list(d.items())\n", "\n", "for k, v in d.items():\n", " print(str(k) + ' => ' + str(v))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Na początek proste dodawanie (pamiętamy o wcięciach, ':' oraz braku '{ }')\n", "\n", "def suma(a, b): \n", " return a + b\n", " \n", "if suma(1,3) == 4: print(\"ok\") # można w jednej linijce" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Python wspiera wartości domyślne funkcji. Jaki będzie wynik?\n", "def suma(a, \n", " b, \n", " wa=1, \n", " wb=3):\n", " return wa * a + wb * b\n", "\n", "suma(1,1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "suma(1, 3, 2, 1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Zamieniliśmy kolejność, odwołując się po identyfikatorach. Czy teraz się wyjdzie?\n", "suma(1, 3, wb=2, wa=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(suma(1, 3, wa=2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co ta funkcja robi?\n", "# Ile wartości ona zwraca?\n", "def f(arr):\n", " n = x = arr[0]\n", " for a in arr:\n", " if n > a:\n", " n = a\n", " if x < a:\n", " x = a\n", " return n, x\n", "\n", "print(f([2,3,1,4]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Jak to przechwycić?\n", "a = f([2,3,1,4])\n", "print(a)\n", "a, b = f([2,3,1,4])\n", "print(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czym jest x?\n", "x = f([2,3,1,4])\n", "type(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Przkład operacji a, b = b, a (swap)\n", "a = 1\n", "b = 2\n", "a, b = b, a\n", "print('a = ' + str(a))\n", "print('b = ' + str(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Taki inny unzip\n", "x = ('ala','ma','kota')\n", "a, b, c = x\n", "print('a = ' + str(a))\n", "print('b = ' + str(b))\n", "print('c = ' + str(c))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pytanie za zero punktów. Co zwraca funkcja f?\n", "def f(wa=1, wb=1): \n", " def g(a, b):\n", " return a * wa + b * wb;\n", " return g\n", "\n", "f(1,3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# W Javie czym musimy się posłużyć, żeby uzyskać taki efekt? \n", "wazona = f(0, 1)\n", "wazona" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wazona(1, 3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Gratisowa metoda listy. Wynik?\n", "arr = [-3, 2, 1, 4]\n", "arr.sort()\n", "arr" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "arr.sort(reverse=True)\n", "arr" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "def mykey(x):\n", " return abs(x)\n", "arr.sort(key=mykey)\n", "arr" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Możemy to zrobić 'inline' wykorzystując funkcje lambda.\n", "arr.sort(key=lambda x: abs(x))\n", "arr" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Utrwalmy funkcje lambda. Jaki będzie wynik?\n", "f = lambda a, b: a - b\n", "print(f(1,2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "g = lambda a, b: a + b\n", "print(g(1,2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz? \n", "f, g = g, f\n", "print(f(1,2))\n", "print(g(1,2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Various" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Complex numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Python obsługuje liczby zespolone\n", "1+3j" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czym jest moduł liczby zepolonej?\n", "abs(1+3j)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(1+3j)*(2-1j)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generators (yield)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Normalnie, po wykonaniu funkcji, jej stan lokalny jest niszczony. Ale...\n", "# Co robi ten kod?\n", "\n", "def whatdoido():\n", " a, b = 0, 1\n", " while True:\n", " yield a\n", " a, b = b, a + b\n", "\n", "print(whatdoido())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wynik?\n", "g = whatdoido()\n", "print(next(g))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A teraz?\n", "print(next(g))\n", "print(next(g))\n", "print(next(g))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można tak\n", "for i in range(10):\n", " print(next(g))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co teraz chcemy otrzymać?\n", "for v in whatdoido():\n", " if v > 100:\n", " break\n", " print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ten kod tworzy wszytkie k-elementowe kombinacje z iterowalnego obiektu \n", "# (np. listy, ciągu znaków). Są tutaj dwie fajne rzeczy.\n", "def combinations(iterable, k):\n", " # combinations('ABCD', 2) --> AB AC AD BC BD CD\n", " # combinations(range(4), 3) --> 012 013 023 123\n", " pool = tuple(iterable)\n", " print (pool)\n", " n = len(pool)\n", " if k > n:\n", " return\n", " indices = list(range(k))\n", " print(indices)\n", " yield tuple(pool[i] for i in indices)\n", " while True:\n", " for i in reversed(range(k)):\n", " if indices[i] != i + n - k:\n", " break\n", " # Pierwsza fajna rzecz\n", " else:\n", " return\n", " indices[i] += 1\n", " for j in range(i+1, k):\n", " indices[j] = indices[j-1] + 1\n", " yield tuple(pool[i] for i in indices)\n", " \n", "pairs = combinations('ABCD', 2)\n", "print(pairs)\n", "# Druga fajna rzecz. Ale musimy uważać, przy tworzeniu generatora (return)\n", "for pair in pairs:\n", " print(pair)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pierwsze trzy pary, które mają A i G w środku\n", "pairs = combinations('ABCDEFGH', 3)\n", "found = 0\n", "for pair in pairs:\n", " if 'A' in pair and 'G' in pair and found < 3:\n", " found += 1\n", " print(pair)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Build-in functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dwa przykłady poniżej są fajne, bo można np. wczytać sobie z jednego skrytpu drugi, \n", "# i go wykonać\n", "x=1\n", "eval('max([x,2,-2,3])')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "exec('import math; print(math.sin(2*math.pi))')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Funkcje logiczne\n", "print(all([True, False, True]))\n", "print(any([True, False, True]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Funkcje matematyczne\n", "print(sum([1,2,3]))\n", "print(min([1,2,3]))\n", "print(max([1,2,3]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Inne funkcje matematyczne\n", "print(abs(-12))\n", "print(round(3.14159, 3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pamiętamy? Konwersja w pythonie jest łatwa.\n", "print(float(12))\n", "print(int(12.7))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(str(123))\n", "print(str([1,2,3]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Znak -> numer w unicode i na odwrót. \n", "print(ord('a'))\n", "print(chr(98))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Fajna funkcja. Do debugowania\n", "print(type('ala ma kota'))\n", "print(type([1,2,3]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Global" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Trochę o zmiennych globalnych. \n", "text = 'ala ma kota'\n", "\n", "def a():\n", " print('a: ' + text) \n", "def b():\n", " print('b: ' + text)\n", " text = 'ala ma psa' " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wynik?\n", "a()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wynik?\n", "b()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Zmienne globalne są niebezpieczne. Python chce, żebyśmy mu dali znać,\n", "# że wiemy co robimy :)\n", "text = 'ala ma kota'\n", "def c():\n", " global text\n", " print('c: ' + text)\n", " text = 'ala ma psa'\n", "\n", "c()\n", "print(text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Comprehensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# To są fajne rzeczy. Warto zapamiętać - super oszczędność kodu!\n", "# Jakby wyglądało 'klasyczne' przeniesienie alementow jednej listy do drugiej + coś jeszcze\n", "\n", "arr = [0,1,2,3,4,5]\n", "new = []\n", "for a in arr:\n", " new.append('A' + str(a))\n", "new" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# W pythonie można tak:\n", "\n", "arr = [0,1,2,3,4,5]\n", "new = ['A' + str(a) for a in arr]\n", "new" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można dodać warunek. Czyli ogólnie: [funkcja for if]\n", "arr = [0,1,2,3,4,5]\n", "new = ['A' + str(a) for a in arr if a % 2 == 0]\n", "new" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co to robi?\n", "arr = [0,13,2,4,11]\n", "sum([1 for a in arr if a % 2 == 0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Chcemy wszystkie pierwsze litery wyrazów zamienić na wielkie\n", "text = 'to jest krótki text nie na temat'\n", "splitted = text.split()\n", "splitted" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "big = [x[0].upper() + x[1:] for x in splitted]\n", "big" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Trochę długaśne. Swoją drogą - fajne wykorzystanie str.join.\n", "\" \".join(big)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można to zrobić krócej:\n", "text = 'to jest krótki text nie na temat'\n", "print(\" \".join([x[0].upper() + x[1:] for x in text.split()]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Co, gdybyśmy chcieli coś zrobić, z każdą komórka 2d macierzy?\n", "\n", "m = [[0,1,1,0],\n", " [1,0,1,0],\n", " [0,1,0,1],\n", " [1,0,0,1]]\n", "nm = [[1 - cell for cell in row] for row in m]\n", "print(m)\n", "print(nm)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tutaj pamietamy o klamrach \n", "# Co to robi?\n", "przedmioty = ('matematyka', 'fizyka', 'chemia')\n", "slownik = {p: len(p) for p in przedmioty}\n", "slownik" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Classes" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Krótko omówimy klasy (tak, python jest obiektowy)\n", "# __init__, self\n", "\n", "class Circle:\n", " \n", " def __init__(self, radius):\n", " self.radius = radius \n", " self.costam = 2\n", " \n", " def area(self):\n", " from math import pi\n", " self.size = pi * self.radius**2\n", " return self.size\n", " \n", " def set_radius(self, radius):\n", " self.radius = radius \n", " \n", "c = Circle(3)\n", "print(c.area())\n", "c.set_radius(5) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(c.radius)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# W pythonie nie ma '{ }' więc jak zrobić pustą klasę?\n", "# Pamiętamy, że w pythonie nie trzeba deklarować.\n", "# Wynik?\n", "\n", "class Container:\n", " pass\n", "\n", "def compute(container):\n", " return container.size**2\n", "\n", "c = Container\n", "c.size = 2;\n", "\n", "compute(c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Atrybuty 'statyczne' i dla instancji.\n", "class Przedmiot:\n", " acoto = 12\n", " alefajnie = 2\n", " def __init__(self, nazwa):\n", " self.nazwa = nazwa\n", " \n", " \n", "p = Przedmiot('kck')\n", "p.nazwa" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(p.acoto)\n", "print(Przedmiot.alefajnie)\n", "print(Przedmiot.acoto)\n", "Przedmiot.acoto = 5\n", "print(Przedmiot.acoto)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wygląda brzydko. A jak robiliśmy print(lista) to było ładnie. \n", "print(p)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można temu zaradzić\n", "class Przedmiot: \n", " def __init__(self, nazwa):\n", " self.nazwa = nazwa\n", " \n", " def __repr__(self):\n", " return 'Przedmiot o nazwie ' + self.nazwa\n", " \n", "p = Przedmiot('KCK')\n", "print(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Duck typing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "class Circle:\n", " def __init__(self, radius):\n", " self.radius = radius \n", " def area(self):\n", " from math import pi\n", " return pi * self.radius**2\n", "\n", "class Square:\n", " def __init__(self, w):\n", " self.w = w\n", " def area(self):\n", " return self.w**2\n", " \n", "class Line:\n", " pass\n", " \n", "def get_shape():\n", " from random import choice\n", " return choice([Square(4), Circle(4), Line()])\n", " \n", "shape = get_shape()\n", "shape.area()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Files" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Pisanie do pliku jest proste\n", "f = open('test.txt','w')\n", "for i in range(6):\n", " f.write('To jest linia {}\\n'.format(i))\n", "f.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cat test.txt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Czytanie też. Jak iterujemy plik, to czytamy linie.\n", "f = open('test.txt')\n", "for line in f:\n", " print(line.strip())\n", "f.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można tak\n", "with open('test.txt') as f:\n", " for line in f:\n", " print(line.strip())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Można od razu wczytac wsystkie linie i dalej używać.\n", "with open('test.txt') as f:\n", " lines = f.readlines()\n", "lines[1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "http://www.learnpython.org/en/Welcome " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "https://www.hackerrank.com/domains/python/py-introduction" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "\n", "plt.figure(figsize=(5, 5))\n", "plt.plot([100,200,300,400],[0.1,0.2,0.8,0.9])\n", "#plt.savefig('myplot.pdf')\n", "#plt.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "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.5.0" } }, "nbformat": 4, "nbformat_minor": 1 }