{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# В домашней работе вам надо будет сгенерировать свой вариант следующим образом\n", "def generate(key, problems=4, variants=4):\n", " r = 0\n", " for c in key:\n", " r += ord(c)\n", " result = []\n", " for j in range(problems):\n", " result.append(chr(ord('A') + j) + str(r % variants + 1))\n", " r //= variants\n", " return result" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['A1', 'B1', 'C2', 'D3']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "generate(\"Зобнин Алексей Игоревич\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Рассмотрим модуль itertools\n", "# Подключить его можно так:\n", "import itertools\n", "\n", "# Но тогда придется писать itertools. перед каждым именем функции из этого модуля\n", "# Поэтому сделаем так:\n", "from itertools import *\n", "\n", "# Вообще-то так писать в больших проектах не рекомендуется,\n", "# чтобы не засорять пространства имен. Лучше подключать только нужные имена" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "s = [1, 2, 3, 4]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3, 4)\n", "(1, 2, 4, 3)\n", "(1, 3, 2, 4)\n", "(1, 3, 4, 2)\n", "(1, 4, 2, 3)\n", "(1, 4, 3, 2)\n", "(2, 1, 3, 4)\n", "(2, 1, 4, 3)\n", "(2, 3, 1, 4)\n", "(2, 3, 4, 1)\n", "(2, 4, 1, 3)\n", "(2, 4, 3, 1)\n", "(3, 1, 2, 4)\n", "(3, 1, 4, 2)\n", "(3, 2, 1, 4)\n", "(3, 2, 4, 1)\n", "(3, 4, 1, 2)\n", "(3, 4, 2, 1)\n", "(4, 1, 2, 3)\n", "(4, 1, 3, 2)\n", "(4, 2, 1, 3)\n", "(4, 2, 3, 1)\n", "(4, 3, 1, 2)\n", "(4, 3, 2, 1)\n" ] } ], "source": [ "# Сгенерируем перестановки элементов списка\n", "for p in permutations(s):\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(list(itertools.permutations(s)))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('h', 'e', 'l', 'l', 'o')\n", "('h', 'e', 'l', 'o', 'l')\n", "('h', 'e', 'l', 'l', 'o')\n", "('h', 'e', 'l', 'o', 'l')\n", "('h', 'e', 'o', 'l', 'l')\n", "('h', 'e', 'o', 'l', 'l')\n", "('h', 'l', 'e', 'l', 'o')\n", "('h', 'l', 'e', 'o', 'l')\n", "('h', 'l', 'l', 'e', 'o')\n", "('h', 'l', 'l', 'o', 'e')\n", "('h', 'l', 'o', 'e', 'l')\n", "('h', 'l', 'o', 'l', 'e')\n", "('h', 'l', 'e', 'l', 'o')\n", "('h', 'l', 'e', 'o', 'l')\n", "('h', 'l', 'l', 'e', 'o')\n", "('h', 'l', 'l', 'o', 'e')\n", "('h', 'l', 'o', 'e', 'l')\n", "('h', 'l', 'o', 'l', 'e')\n", "('h', 'o', 'e', 'l', 'l')\n", "('h', 'o', 'e', 'l', 'l')\n", "('h', 'o', 'l', 'e', 'l')\n", "('h', 'o', 'l', 'l', 'e')\n", "('h', 'o', 'l', 'e', 'l')\n", "('h', 'o', 'l', 'l', 'e')\n", "('e', 'h', 'l', 'l', 'o')\n", "('e', 'h', 'l', 'o', 'l')\n", "('e', 'h', 'l', 'l', 'o')\n", "('e', 'h', 'l', 'o', 'l')\n", "('e', 'h', 'o', 'l', 'l')\n", "('e', 'h', 'o', 'l', 'l')\n", "('e', 'l', 'h', 'l', 'o')\n", "('e', 'l', 'h', 'o', 'l')\n", "('e', 'l', 'l', 'h', 'o')\n", "('e', 'l', 'l', 'o', 'h')\n", "('e', 'l', 'o', 'h', 'l')\n", "('e', 'l', 'o', 'l', 'h')\n", "('e', 'l', 'h', 'l', 'o')\n", "('e', 'l', 'h', 'o', 'l')\n", "('e', 'l', 'l', 'h', 'o')\n", "('e', 'l', 'l', 'o', 'h')\n", "('e', 'l', 'o', 'h', 'l')\n", "('e', 'l', 'o', 'l', 'h')\n", "('e', 'o', 'h', 'l', 'l')\n", "('e', 'o', 'h', 'l', 'l')\n", "('e', 'o', 'l', 'h', 'l')\n", "('e', 'o', 'l', 'l', 'h')\n", "('e', 'o', 'l', 'h', 'l')\n", "('e', 'o', 'l', 'l', 'h')\n", "('l', 'h', 'e', 'l', 'o')\n", "('l', 'h', 'e', 'o', 'l')\n", "('l', 'h', 'l', 'e', 'o')\n", "('l', 'h', 'l', 'o', 'e')\n", "('l', 'h', 'o', 'e', 'l')\n", "('l', 'h', 'o', 'l', 'e')\n", "('l', 'e', 'h', 'l', 'o')\n", "('l', 'e', 'h', 'o', 'l')\n", "('l', 'e', 'l', 'h', 'o')\n", "('l', 'e', 'l', 'o', 'h')\n", "('l', 'e', 'o', 'h', 'l')\n", "('l', 'e', 'o', 'l', 'h')\n", "('l', 'l', 'h', 'e', 'o')\n", "('l', 'l', 'h', 'o', 'e')\n", "('l', 'l', 'e', 'h', 'o')\n", "('l', 'l', 'e', 'o', 'h')\n", "('l', 'l', 'o', 'h', 'e')\n", "('l', 'l', 'o', 'e', 'h')\n", "('l', 'o', 'h', 'e', 'l')\n", "('l', 'o', 'h', 'l', 'e')\n", "('l', 'o', 'e', 'h', 'l')\n", "('l', 'o', 'e', 'l', 'h')\n", "('l', 'o', 'l', 'h', 'e')\n", "('l', 'o', 'l', 'e', 'h')\n", "('l', 'h', 'e', 'l', 'o')\n", "('l', 'h', 'e', 'o', 'l')\n", "('l', 'h', 'l', 'e', 'o')\n", "('l', 'h', 'l', 'o', 'e')\n", "('l', 'h', 'o', 'e', 'l')\n", "('l', 'h', 'o', 'l', 'e')\n", "('l', 'e', 'h', 'l', 'o')\n", "('l', 'e', 'h', 'o', 'l')\n", "('l', 'e', 'l', 'h', 'o')\n", "('l', 'e', 'l', 'o', 'h')\n", "('l', 'e', 'o', 'h', 'l')\n", "('l', 'e', 'o', 'l', 'h')\n", "('l', 'l', 'h', 'e', 'o')\n", "('l', 'l', 'h', 'o', 'e')\n", "('l', 'l', 'e', 'h', 'o')\n", "('l', 'l', 'e', 'o', 'h')\n", "('l', 'l', 'o', 'h', 'e')\n", "('l', 'l', 'o', 'e', 'h')\n", "('l', 'o', 'h', 'e', 'l')\n", "('l', 'o', 'h', 'l', 'e')\n", "('l', 'o', 'e', 'h', 'l')\n", "('l', 'o', 'e', 'l', 'h')\n", "('l', 'o', 'l', 'h', 'e')\n", "('l', 'o', 'l', 'e', 'h')\n", "('o', 'h', 'e', 'l', 'l')\n", "('o', 'h', 'e', 'l', 'l')\n", "('o', 'h', 'l', 'e', 'l')\n", "('o', 'h', 'l', 'l', 'e')\n", "('o', 'h', 'l', 'e', 'l')\n", "('o', 'h', 'l', 'l', 'e')\n", "('o', 'e', 'h', 'l', 'l')\n", "('o', 'e', 'h', 'l', 'l')\n", "('o', 'e', 'l', 'h', 'l')\n", "('o', 'e', 'l', 'l', 'h')\n", "('o', 'e', 'l', 'h', 'l')\n", "('o', 'e', 'l', 'l', 'h')\n", "('o', 'l', 'h', 'e', 'l')\n", "('o', 'l', 'h', 'l', 'e')\n", "('o', 'l', 'e', 'h', 'l')\n", "('o', 'l', 'e', 'l', 'h')\n", "('o', 'l', 'l', 'h', 'e')\n", "('o', 'l', 'l', 'e', 'h')\n", "('o', 'l', 'h', 'e', 'l')\n", "('o', 'l', 'h', 'l', 'e')\n", "('o', 'l', 'e', 'h', 'l')\n", "('o', 'l', 'e', 'l', 'h')\n", "('o', 'l', 'l', 'h', 'e')\n", "('o', 'l', 'l', 'e', 'h')\n" ] } ], "source": [ "# Переставлять можно элементы любой итерируемой сущности. Например, буквы в строке\n", "for p in permutations(\"hello\"):\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "120" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(list(permutations(\"hello\")))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "60" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# В предыдущем списке были повторы из-за повторяющейся буквы l\n", "# Контейнер set позволяет от них избавиться\n", "len(set(permutations(\"hello\")))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('a', 'b')\n", "('a', 'c')\n", "('a', 'd')\n", "('b', 'c')\n", "('b', 'd')\n", "('c', 'd')\n" ] } ], "source": [ "# Следующая функция - itertools.combinations\n", "# Это сочетания из k элементов\n", "for comb in combinations(\"abcd\", 2):\n", " print(comb)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('d', 'c', 'b')\n", "('d', 'c', 'a')\n", "('d', 'b', 'a')\n", "('c', 'b', 'a')\n" ] } ], "source": [ "for comb in combinations(\"dcba\", 3):\n", " print(comb)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('a', 'a', 'a')\n", "('a', 'a', 'b')\n", "('a', 'a', 'c')\n", "('a', 'a', 'd')\n", "('a', 'b', 'b')\n", "('a', 'b', 'c')\n", "('a', 'b', 'd')\n", "('a', 'c', 'c')\n", "('a', 'c', 'd')\n", "('a', 'd', 'd')\n", "('b', 'b', 'b')\n", "('b', 'b', 'c')\n", "('b', 'b', 'd')\n", "('b', 'c', 'c')\n", "('b', 'c', 'd')\n", "('b', 'd', 'd')\n", "('c', 'c', 'c')\n", "('c', 'c', 'd')\n", "('c', 'd', 'd')\n", "('d', 'd', 'd')\n" ] } ], "source": [ "# Сочетания с повторениями\n", "for comb in combinations_with_replacement(\"abcd\", 3):\n", " print(comb)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['__doc__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " '_grouper',\n", " '_tee',\n", " '_tee_dataobject',\n", " 'accumulate',\n", " 'chain',\n", " 'combinations',\n", " 'combinations_with_replacement',\n", " 'compress',\n", " 'count',\n", " 'cycle',\n", " 'dropwhile',\n", " 'filterfalse',\n", " 'groupby',\n", " 'islice',\n", " 'permutations',\n", " 'product',\n", " 'repeat',\n", " 'starmap',\n", " 'takewhile',\n", " 'tee',\n", " 'zip_longest']" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Что еще есть в модуле itertools?\n", "dir(itertools)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Обратите внимание, что имена с подчеркиваниями - скрытые или зарезервированные" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 'a')\n", "(1, 'b')\n", "(2, 'a')\n", "(2, 'b')\n", "(3, 'a')\n", "(3, 'b')\n" ] } ], "source": [ "# Функция itertools.product - декартово произведение\n", "for elem in product([1,2,3], \"ab\"):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 a\n", "1 b\n", "2 a\n", "2 b\n", "3 a\n", "3 b\n" ] } ], "source": [ "for number in [1,2,3]:\n", " for letter in \"ab\":\n", " print(number, letter)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": true }, "outputs": [], "source": [ "l = [[1,2,3], \"abc\", [3.14, 2.718], \"hello\"]" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 'a', 3.14, 'h')\n", "(1, 'a', 3.14, 'e')\n", "(1, 'a', 3.14, 'l')\n", "(1, 'a', 3.14, 'l')\n", "(1, 'a', 3.14, 'o')\n", "(1, 'a', 2.718, 'h')\n", "(1, 'a', 2.718, 'e')\n", "(1, 'a', 2.718, 'l')\n", "(1, 'a', 2.718, 'l')\n", "(1, 'a', 2.718, 'o')\n", "(1, 'b', 3.14, 'h')\n", "(1, 'b', 3.14, 'e')\n", "(1, 'b', 3.14, 'l')\n", "(1, 'b', 3.14, 'l')\n", "(1, 'b', 3.14, 'o')\n", "(1, 'b', 2.718, 'h')\n", "(1, 'b', 2.718, 'e')\n", "(1, 'b', 2.718, 'l')\n", "(1, 'b', 2.718, 'l')\n", "(1, 'b', 2.718, 'o')\n", "(1, 'c', 3.14, 'h')\n", "(1, 'c', 3.14, 'e')\n", "(1, 'c', 3.14, 'l')\n", "(1, 'c', 3.14, 'l')\n", "(1, 'c', 3.14, 'o')\n", "(1, 'c', 2.718, 'h')\n", "(1, 'c', 2.718, 'e')\n", "(1, 'c', 2.718, 'l')\n", "(1, 'c', 2.718, 'l')\n", "(1, 'c', 2.718, 'o')\n", "(2, 'a', 3.14, 'h')\n", "(2, 'a', 3.14, 'e')\n", "(2, 'a', 3.14, 'l')\n", "(2, 'a', 3.14, 'l')\n", "(2, 'a', 3.14, 'o')\n", "(2, 'a', 2.718, 'h')\n", "(2, 'a', 2.718, 'e')\n", "(2, 'a', 2.718, 'l')\n", "(2, 'a', 2.718, 'l')\n", "(2, 'a', 2.718, 'o')\n", "(2, 'b', 3.14, 'h')\n", "(2, 'b', 3.14, 'e')\n", "(2, 'b', 3.14, 'l')\n", "(2, 'b', 3.14, 'l')\n", "(2, 'b', 3.14, 'o')\n", "(2, 'b', 2.718, 'h')\n", "(2, 'b', 2.718, 'e')\n", "(2, 'b', 2.718, 'l')\n", "(2, 'b', 2.718, 'l')\n", "(2, 'b', 2.718, 'o')\n", "(2, 'c', 3.14, 'h')\n", "(2, 'c', 3.14, 'e')\n", "(2, 'c', 3.14, 'l')\n", "(2, 'c', 3.14, 'l')\n", "(2, 'c', 3.14, 'o')\n", "(2, 'c', 2.718, 'h')\n", "(2, 'c', 2.718, 'e')\n", "(2, 'c', 2.718, 'l')\n", "(2, 'c', 2.718, 'l')\n", "(2, 'c', 2.718, 'o')\n", "(3, 'a', 3.14, 'h')\n", "(3, 'a', 3.14, 'e')\n", "(3, 'a', 3.14, 'l')\n", "(3, 'a', 3.14, 'l')\n", "(3, 'a', 3.14, 'o')\n", "(3, 'a', 2.718, 'h')\n", "(3, 'a', 2.718, 'e')\n", "(3, 'a', 2.718, 'l')\n", "(3, 'a', 2.718, 'l')\n", "(3, 'a', 2.718, 'o')\n", "(3, 'b', 3.14, 'h')\n", "(3, 'b', 3.14, 'e')\n", "(3, 'b', 3.14, 'l')\n", "(3, 'b', 3.14, 'l')\n", "(3, 'b', 3.14, 'o')\n", "(3, 'b', 2.718, 'h')\n", "(3, 'b', 2.718, 'e')\n", "(3, 'b', 2.718, 'l')\n", "(3, 'b', 2.718, 'l')\n", "(3, 'b', 2.718, 'o')\n", "(3, 'c', 3.14, 'h')\n", "(3, 'c', 3.14, 'e')\n", "(3, 'c', 3.14, 'l')\n", "(3, 'c', 3.14, 'l')\n", "(3, 'c', 3.14, 'o')\n", "(3, 'c', 2.718, 'h')\n", "(3, 'c', 2.718, 'e')\n", "(3, 'c', 2.718, 'l')\n", "(3, 'c', 2.718, 'l')\n", "(3, 'c', 2.718, 'o')\n" ] } ], "source": [ "# Декартово перемножить списки внутри нашего l можно с помощью звездочки:\n", "for elem in product(*l):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "([1, 2, 3],)\n", "('abc',)\n", "([3.14, 2.718],)\n", "('hello',)\n" ] } ], "source": [ "# Вопрос из зала: что будет, если не поставить звездочку? Вот ответ:\n", "for elem in product(l):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['__doc__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " '_grouper',\n", " '_tee',\n", " '_tee_dataobject',\n", " 'accumulate',\n", " 'chain',\n", " 'combinations',\n", " 'combinations_with_replacement',\n", " 'compress',\n", " 'count',\n", " 'cycle',\n", " 'dropwhile',\n", " 'filterfalse',\n", " 'groupby',\n", " 'islice',\n", " 'permutations',\n", " 'product',\n", " 'repeat',\n", " 'starmap',\n", " 'takewhile',\n", " 'tee',\n", " 'zip_longest']" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(itertools)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 a\n", "1 b\n", "2 c\n", "3 a\n", "4 b\n", "5 c\n", "6 a\n", "7 b\n", "8 c\n", "9 a\n", "10 b\n", "11 c\n", "12 a\n", "13 b\n", "14 c\n", "15 a\n", "16 b\n", "17 c\n", "18 a\n", "19 b\n", "20 c\n" ] } ], "source": [ "# Функция itertools.cycle позволяет бесконечно перебирать элементы по кругу\n", "# Мы в этом примере воспользуемся enumerate, чтобы цикл стал конечным\n", "for i, elem in enumerate(cycle(\"abc\")):\n", " if i > 20:\n", " break\n", " print(i, elem)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "5\n", "8\n", "11\n", "14\n", "17\n", "20\n", "23\n", "26\n", "29\n" ] } ], "source": [ "# Теперь поговорим о генераторах\n", "# Их можно писать как обычные функции, но с оператором yield вместо return\n", "# Вот такой генератор будет строить первые n членов арифметической прогрессии\n", "def progression(a, d, n):\n", " x = a\n", " i = 1\n", " while i <= n:\n", " yield x\n", " x += d\n", " i += 1\n", " \n", "for elem in progression(2, 3, 10):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [], "source": [ "g = progression(2, 3, 10)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__del__',\n", " '__delattr__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__iter__',\n", " '__le__',\n", " '__lt__',\n", " '__name__',\n", " '__ne__',\n", " '__new__',\n", " '__next__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'close',\n", " 'gi_code',\n", " 'gi_frame',\n", " 'gi_running',\n", " 'send',\n", " 'throw']" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(g)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# На самом деле там внутри есть метод __next__, который неявно вызывается в цикле for\n", "g.__next__()" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "23" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "26" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "29" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.__next__()" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": false }, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mg\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__next__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m: " ] } ], "source": [ "# На одиннадцатом шаге происходит исключение StopIteration (мы же просили 10 членов!)\n", "g.__next__()" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n" ] } ], "source": [ "# Генератор чисел Фибоначчи (где первые два числа - a и b)\n", "def fib(a, b, n):\n", " i = 1\n", " while i <= n:\n", " yield a\n", " a, b = b, a + b\n", " i += 1\n", " \n", "for elem in fib(1, 1, 10):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# А вот так можно было бы решить задачу F из контеста про циклы\n", "# (про последовательность натуральных чисел, где каждое число i повторяется i раз)\n", "# Только учтите, что yield from работает начиная с версии 3.3, а в Контесте - 3.2\n", "def sequence():\n", " i = 1\n", " while True:\n", " yield from [i] * i\n", " i += 1\n", " \n", "# Вот другое решение той же задачи\n", "def sequence():\n", " i = 1\n", " while True:\n", " for j in in range(i):\n", " yield i\n", " i += 1\n", " \n", " " ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "2\n", "3\n", "3\n" ] } ], "source": [ "for i, elem in enumerate(sequence()):\n", " print(elem)\n", " if i >= 5 - 1:\n", " break" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Вспомним, как мы подсчитывали буквы в строке\n", "s = \"Студенты Высшей школы экономики\"\n", "letters = {}\n", "for c in s:\n", " letters[c] = letters.get(c, 0) + 1" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Counter({' ': 3, 'к': 3, 'о': 3, 'ы': 3, 'е': 2, 'т': 2, 'ш': 2, 'н': 2, 'и': 2, 'д': 1, 'э': 1, 'м': 1, 'й': 1, 'л': 1, 'у': 1, 'В': 1, 'С': 1, 'с': 1})\n" ] } ], "source": [ "# В модуле collections есть удобный класс Counter,\n", "# который уже знает, что 0 - это значение по умолчанию\n", "import collections\n", "s = \"Студенты Высшей школы экономики\"\n", "letters = collections.Counter()\n", "for c in s:\n", " letters[c] += 1 # не надо думать о том, есть ли такой ключ в словаре\n", "\n", "# К тому же, Counter сразу выдает элементы в порядке убывания частоты \n", "print(letters)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "defaultdict(, {'школы': {'ш', 'к', 'о', 'ы', 'л'}, 'Студенты': {'д', 'е', 'т', 'н', 'ы', 'у', 'С'}, 'Высшей': {'е', 'ш', 'й', 'ы', 'В', 'с'}, 'экономики': {'э', 'н', 'и', 'к', 'м', 'о'}})\n" ] } ], "source": [ "# collections.defaultdict - более общая конструкция: словарь со значением по умолчанию\n", "# Counter похож на defaultdict(int)\n", "# В этом искусственном примере мы сопоставляем словам множества их букв\n", "import collections\n", "s = \"Студенты Высшей школы экономики\"\n", "letters = collections.defaultdict(set)\n", "for word in s.split(\" \"):\n", " for c in word:\n", " letters[word].add(c) \n", " \n", "print(letters)" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['ByteString',\n", " 'Callable',\n", " 'ChainMap',\n", " 'Container',\n", " 'Counter',\n", " 'Hashable',\n", " 'ItemsView',\n", " 'Iterable',\n", " 'Iterator',\n", " 'KeysView',\n", " 'Mapping',\n", " 'MappingView',\n", " 'MutableMapping',\n", " 'MutableSequence',\n", " 'MutableSet',\n", " 'OrderedDict',\n", " 'Sequence',\n", " 'Set',\n", " 'Sized',\n", " 'UserDict',\n", " 'UserList',\n", " 'UserString',\n", " 'ValuesView',\n", " '_Link',\n", " '__all__',\n", " '__builtins__',\n", " '__cached__',\n", " '__doc__',\n", " '__file__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__path__',\n", " '__spec__',\n", " '_chain',\n", " '_class_template',\n", " '_collections_abc',\n", " '_count_elements',\n", " '_eq',\n", " '_field_template',\n", " '_heapq',\n", " '_iskeyword',\n", " '_itemgetter',\n", " '_proxy',\n", " '_recursive_repr',\n", " '_repeat',\n", " '_repr_template',\n", " '_starmap',\n", " '_sys',\n", " 'abc',\n", " 'defaultdict',\n", " 'deque',\n", " 'namedtuple']" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(collections)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Вопрос из зала про queue\n", "import queue" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['Empty',\n", " 'Full',\n", " 'LifoQueue',\n", " 'PriorityQueue',\n", " 'Queue',\n", " '__all__',\n", " '__builtins__',\n", " '__cached__',\n", " '__doc__',\n", " '__file__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " 'deque',\n", " 'heappop',\n", " 'heappush',\n", " 'threading',\n", " 'time']" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(queue)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "range" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Вопрос из зала про range\n", "type(range(100))" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0,\n", " 1,\n", " 2,\n", " 3,\n", " 4,\n", " 5,\n", " 6,\n", " 7,\n", " 8,\n", " 9,\n", " 10,\n", " 11,\n", " 12,\n", " 13,\n", " 14,\n", " 15,\n", " 16,\n", " 17,\n", " 18,\n", " 19,\n", " 20,\n", " 21,\n", " 22,\n", " 23,\n", " 24,\n", " 25,\n", " 26,\n", " 27,\n", " 28,\n", " 29,\n", " 30,\n", " 31,\n", " 32,\n", " 33,\n", " 34,\n", " 35,\n", " 36,\n", " 37,\n", " 38,\n", " 39,\n", " 40,\n", " 41,\n", " 42,\n", " 43,\n", " 44,\n", " 45,\n", " 46,\n", " 47,\n", " 48,\n", " 49,\n", " 50,\n", " 51,\n", " 52,\n", " 53,\n", " 54,\n", " 55,\n", " 56,\n", " 57,\n", " 58,\n", " 59,\n", " 60,\n", " 61,\n", " 62,\n", " 63,\n", " 64,\n", " 65,\n", " 66,\n", " 67,\n", " 68,\n", " 69,\n", " 70,\n", " 71,\n", " 72,\n", " 73,\n", " 74,\n", " 75,\n", " 76,\n", " 77,\n", " 78,\n", " 79,\n", " 80,\n", " 81,\n", " 82,\n", " 83,\n", " 84,\n", " 85,\n", " 86,\n", " 87,\n", " 88,\n", " 89,\n", " 90,\n", " 91,\n", " 92,\n", " 93,\n", " 94,\n", " 95,\n", " 96,\n", " 97,\n", " 98,\n", " 99]" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(100))" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4, 5]" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(6))" ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# Вот как можно было бы реализовать генератор range (с одним аргументом)\n", "def range(n):\n", " i = 0\n", " while i < n:\n", " yield i\n", " i += 1\n", "\n", "for c in range(10):\n", " print(c)" ] }, { "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.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }