Различия между версиями 6 и 7
Версия 6 от 2018-07-07 21:13:25
Размер: 14334
Редактор: ArsenyMaslennikov
Комментарий: spurce
Версия 7 от 2019-08-24 12:05:56
Размер: 14347
Редактор: ArsenyMaslennikov
Комментарий:
Удаления помечены так. Добавления помечены так.
Строка 21: Строка 21:
   * как и достижение конца тела (что, как известно, эквивалентно `return None`    * как и достижение конца тела (что, как известно, эквивалентно `return None`)
Строка 44: Строка 44:
 * Ещё бывают `параметрические итераторы` (в которых вместо `next()` используется `send(параметр)` и, соответственно `имя = yield значение` связывает параметр именем), н мы их не рассматриваем  * Ещё бывают `параметрические итераторы` (в которых вместо `next(gen)` используется `gen.send(параметр)` и, соответственно, `имя = yield значение` связывает `параметр` именем), но мы их не рассматриваем

Генераторы последовательностей. PyPI. Введение в PyGame

Генераторы

  • позволяют по собственным правилам конструировать вычислимые последовательности
    • даже бесконечные!
  • выглядят как самые обычные функции...
    • ...но в них есть хотя бы одно ключевое слово yield

    • Как только Python видит в теле функции yield, он понимает, что это генератор
  • Отличия функции-генератора от не-генератора:
    • Функция-генератор создаёт и возвращает generator object, по которому можно ходить

      • iterable(gen) == True

      • for i in gen: blabla

      • next(gen)

        • ...кстати, не что иное, как gen.__next__()

        • алгоритм в теле функции выполняется не при её вызове, а именно в методе gen.__next__

      • справедливы все остальные свойства вычислимой последовательности
    • yield не завершает выполнение алгоритма в функции-генераторе, а лишь приостанавливает

      • их может быть сколько угодно
      • next(gen) начинает (соотв. продолжает) выполнение функции до ближайшего yield

    • return в теле функции-генератора означает активацию исключения StopIteration

      • как и достижение конца тела (что, как известно, эквивалентно return None)

    • Пример:
         1 >>> def gen(N):
         2 ...   yield N
         3 ...   yield N//2
         4 ...   yield 0
         5 ... 
         6 >>> p = gen(11)
         7 >>> p
         8 <generator object gen at 0x7f0b3c5b5a40>
         9 >>> next(p)
        10 11
        11 >>> next(p)
        12 5
        13 >>> next(p)
        14 0
        15 >>> next(p)
        16 Traceback (most recent call last):
        17   File "<stdin>", line 1, in <module>
        18 StopIteration
      
      • Любые возвращаемые значения игнорируются
  • Ещё бывают параметрические итераторы (в которых вместо next(gen) используется gen.send(параметр) и, соответственно, имя = yield значение связывает параметр именем), но мы их не рассматриваем

    • TODO положить ссылку

  • Ещё пример:
       1 def gen(a,b):
       2     yield a+b
       3     for i in range(a,b):
       4         if i == 13:
       5             return
       6         yield i
       7     yield b-a
       8 
       9 print("##########")
      10 for i in gen(2,6):
      11     print(i)
      12 print("##########")
      13 for i in gen(11,16):
      14     print(i)
      15 print("##########") 
    
    • Проверить на 2,6 и 11,15:
    • ##########
      8
      2
      3
      4
      5
      4
      ##########
      27
      11
      12
      ##########
  • {*} Руками реализовать range(10,70,2)

       1 def Range(a,b=None,c=1):
       2     if b is None:
       3         a, b = 0, a
       4     while a<b:
       5         yield a
       6         a += c
    
  • {i} Вычисление π с помощью генератора (формула Лейбница для π)

PyPI

  • централизованное хранилище модулей для Python

  • pip3

    • кроссплатформенный!
    • pip3 install <package>

      • в Linux (как и в любой разумной системе) устанавливать что-то прямо в систему может только администратор
        • поэтому, чтобы поставить себе в домашний каталог: pip3 install --user <package>

    • pip3 search <package>

  • Пример:
    • Поиск:
    george@wide:~> pip3 search lorem
    cicero (0.1)                  - Very simple lorem ipsum style text filler module.
    collective.lorem (0.2.3)      - A package that provides dummy content generation.
    collective.loremipsum (0.10)  - Creates dummy content with populated Lorem Ipsum.
    django-real-content (0.1.11)  - Template tags to quickly show real content instead of
                                    lorem ipsum.
    djipsum (1.1.4)               - Django Lorem Ipsum Generator - Command plugin to
                                    generate (fake content data) for Django model.
    lorem-ipsum-generator (0.3)   - Generates random lorem ipsum text
    ipsedixit (1.1.0)             - Lorem ipsum on steroids.
    lipsum (0.1.2)                - A randomised Lorem Ipsum generator library for Python
    py-lorem (1.2)                - Generate mock sentences/paragraphs with the Lorem
                                    Ipsum prose
    lorem (0.1.1)                 - Generator for random text that looks like Latin.
    python-lorem-pixel (1.0.0)    - Grab any number of images from Lorem Pixel easily.
    LoremDB (0.1.0)               - UNKNOWN
    loremipsum (1.0.5)            - A Lorem Ipsum text generator
    moretext (0.1)                - Get dummy Chinese text (lorem ipsum) with Handlino
                                    serivce.
    mydesire (0.0.1)              - Korean version of loremipsum
    pypsum (0.3.0)                - A RESTfull Lorem Ipsum text generator
    pythonipsum (0.2)             - A lorem ipsum generator for the Python world.
    RandomWords (0.2.1)           - A useful module for a random text, e-mails and lorem
                                    ipsum.
    RikerIpsum (1.1)              - Lorem Ipsum generator which uses dialog from Star Trek
                                    to generate English text.
    statlorem (0.5.0)             - Fun and quirky Lorem Ipsum!
    zopyx.ipsumplone (0.3.10)     - Lorem ipsum text and image demo content for Plone
    • Установка:
    george@wide:~> pip3 install lorem --user
    Collecting lorem
      Downloading lorem-0.1.1-py3-none-any.whl
    Installing collected packages: lorem
    Successfully installed lorem-0.1.1
    • Использование:
    >>> import lorem
    >>> help(lorem)
    
    >>> lorem.paragraph()
    'Adipisci consectetur labore voluptatem quiquia non. Quiquia quaerat velit amet non. Voluptatem quisquam adipisci eius etincidunt dolorem tempora. Dolor ipsum eius voluptatem. Quisquam est porro adipisci sed quiquia aliquam.'
    >>> lorem.paragraph()
    'Aliquam numquam tempora aliquam ut. Dolore dolore etincidunt sed neque tempora. Dolor sed est tempora neque. Adipisci amet magnam dolore voluptatem magnam. Porro quaerat etincidunt quaerat est eius quiquia. Aliquam quisquam modi quaerat porro velit. Amet modi etincidunt velit non voluptatem. Etincidunt adipisci dolore tempora numquam quiquia. Consectetur sit eius numquam tempora est modi.'
    >>> lorem.sentence()
    'Est neque quiquia consectetur porro ut ipsum quisquam.'
    >>> lorem.sentence()
    'Velit quisquam aliquam magnam sed labore consectetur quaerat.'
    >>> print(lorem.text())
    Velit est eius amet numquam. Aliquam est tempora aliquam consectetur adipisci dolore. Dolor sed ipsum porro. Dolorem quaerat amet eius porro dolore. Aliquam eius amet dolor etincidunt tempora sit aliquam.
    
    Etincidunt dolor magnam quaerat aliquam ut. Labore labore quisquam etincidunt quiquia sed. Neque numquam velit quiquia. Eius velit consectetur dolore eius adipisci. Quaerat est sit modi neque quisquam modi labore. Sed sed aliquam consectetur. Amet ipsum est non dolorem numquam neque. Tempora sed eius neque.
    
    Porro ipsum numquam quiquia sit ipsum. Velit voluptatem sed ut. Etincidunt modi aliquam quiquia velit porro. Quisquam non voluptatem quaerat ut consectetur. Magnam ipsum est neque labore neque velit. Dolorem ut numquam tempora velit non aliquam aliquam. Amet amet etincidunt consectetur. Adipisci dolorem modi numquam consectetur. Labore quisquam magnam est. Eius adipisci aliquam sed modi.
    
    Consectetur ipsum tempora ipsum voluptatem. Numquam tempora dolore eius dolore ipsum est dolor. Ut adipisci modi sed aliquam. Amet non adipisci ipsum tempora voluptatem. Ipsum quiquia est magnam. Ut aliquam ipsum labore non dolore ipsum amet. Ipsum quaerat velit modi tempora velit modi modi. Amet magnam quiquia porro adipisci quisquam etincidunt. Voluptatem eius sed aliquam.
    
    Sed est amet neque eius quiquia modi dolore. Non magnam labore sit dolore. Etincidunt est sed porro quaerat. Ipsum porro adipisci ut. Quiquia etincidunt quiquia sit velit. Numquam velit labore aliquam amet quisquam quisquam.
    
    Consectetur amet magnam ipsum ipsum eius dolorem numquam. Labore sed etincidunt est amet dolorem amet ipsum. Tempora ut sed voluptatem quiquia labore velit modi. Voluptatem porro sit dolore. Ipsum est velit voluptatem dolor aliquam. Amet neque labore consectetur eius. Sit neque tempora ut aliquam dolor quisquam aliquam. Non numquam neque dolor dolorem dolore labore tempora.
  • sys.path

    >>> import sys
    >>> sys.path
    ['', '/usr/lib64/python35.zip', '/usr/lib64/python3.5', '/usr/lib64/python3.5/plat-linux', '/usr/lib64/python3.5/lib-dynload', '/home/george/.local/lib/python3/site-packages', '/usr/lib64/python3/site-packages', '/usr/lib/python3/site-packages']
    • Конкретно строка /home/george/.local/lib/python3/site-packages

PyGame

  • не забываем о help()

  • огромный пакет, состоящий из множества модулей
  • {*} Линии, примитивные фигуры, ёлки из треугольников

    •    1        import pygame
         2 
         3        def spruce(surface, N, Rect, Color=pygame.Color("darkgreen")):
         4            '''функция рисования ёлки из N одинаковых треугольников
         5            цвета Color
         6            которая помещается в прямоугольник Rect'''
         7            # XXX болванка
         8            #pygame.draw.rect(surface, Color, Rect)
         9            for i in range(N):
        10                points =(   (Rect.x + Rect.w//2, Rect.y + i*Rect.h//N), 
        11                            (Rect.x + Rect.w - 1, Rect.y + (i+1)*Rect.h//N - 1), 
        12                            (Rect.x, Rect.y + (i+1)*Rect.h//N - 1),
        13                        )
        14                pygame.draw.polygon(surface, Color, points)
        15                pygame.draw.polygon(surface, Color//pygame.Color(4,2,1,1), points, 2)
        16 
        17        W,H = 640, 480
        18        pygame.init()
        19        screen = pygame.display.set_mode((W,H))
        20 
        21        spruce(screen, 3, pygame.Rect(10,10,100,200))
        22        spruce(screen, 3, pygame.Rect(140,140,100,100))
        23 
        24        while True:
        25            pygame.display.flip()
      
  • {*} Квадрат, который можно тащить мышью

    •    1        # нарисовать посередине квадрат 30×30 и перемещать его мышкой
         2        import pygame
         3        import random
         4        W,H = 640, 480
         5        SW, SH = 30, 30
         6        
         7        pygame.init()
         8        display = pygame.display.set_mode((W,H))
         9        screen = display.copy()
        10        SCol = pygame.Color(255,200,190,255)
        11        BLACK = pygame.Color("black")
        12        Square = pygame.Rect(W//2-SW//2, H//2-SH//2, SW, SH)
        13         
        14        SCarry = False
        15        while True:
        16            e = pygame.event.wait()
        17            if e.type == pygame.QUIT or e.type == pygame.KEYUP and e.key == 27:
        18                break
        19            elif e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
        20                if Square.collidepoint(e.pos):
        21                    SCarry= True
        22            elif e.type == pygame.MOUSEBUTTONUP and e.button == 1:
        23                if SCarry:
        24                    SCarry = False
        25                    Square.center = e.pos
        26            elif e.type == pygame.MOUSEMOTION and e.buttons[0]:
        27                if SCarry:
        28                    Square.center = e.pos
        29            else:
        30                print(e)
        31            screen.fill(BLACK)
        32            pygame.draw.rect(screen, SCol, Square)
        33            display.blit(screen, (0,0))
        34            pygame.display.flip()
      
  • {*} Анимированный движущийся квадратик (движение растянуто во времени)

    •    1        # нарисовать посередине движущийся квадрат 30×30 и перемещать его мышкой
         2        import pygame
         3        import random
         4        W,H = 640, 480
         5        SW, SH = 30, 30
         6 
         7        pygame.init()
         8        display = pygame.display.set_mode((W,H))
         9        screen = display.copy()
        10        SCol = pygame.Color(255,200,190,255)
        11        BLACK = pygame.Color("black")
        12        Square = pygame.Rect(W//2-SW//2, H//2-SH//2, SW, SH)
        13        Vel = 1,1
        14        pygame.time.set_timer(pygame.USEREVENT+1, 70)
        15        SCarry = False
        16        while True:
        17            e = pygame.event.wait()
        18            if e.type == pygame.QUIT or e.type == pygame.KEYUP and e.key == 27:
        19                break
        20            elif e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
        21                if Square.collidepoint(e.pos):
        22                    SCarry= True
        23            elif e.type == pygame.MOUSEBUTTONUP and e.button == 1:
        24                if SCarry:
        25                    SCarry = False
        26                    Square.center = e.pos
        27            elif e.type == pygame.MOUSEMOTION and e.buttons[0]:
        28                if SCarry:
        29                    Square.center = e.pos
        30            elif e.type == pygame.USEREVENT+1:
        31                if not SCarry:
        32                    Square = Square.move(Vel)
        33            else:
        34                print(e)
        35 
        36            screen.fill(BLACK)
        37            pygame.draw.rect(screen, SCol, Square)
        38            display.blit(screen, (0,0))
        39            pygame.display.flip()
      
  • {i} Несколько квадратиков; иметь возможность плавно тащить мышью каждый

  • {i} Заставить едущий квадрат отражаться от стенок окна

    • <!> Тормоз и газ

  • К зачёту: Совместить две предыдущие.

Python/Summer2017/2017-07-11 (последним исправлял пользователь ArsenyMaslennikov 2019-08-24 12:05:56)