38
Python & Perl Lecture 12 Department of Computer Science Utah State University

Python lecture 12

Embed Size (px)

Citation preview

Page 1: Python lecture 12

Python & Perl

Lecture 12

Department of Computer ScienceUtah State University

Page 2: Python lecture 12

Outline● Iterators● Generators● PIL Basics

Page 3: Python lecture 12

Iterators

Page 4: Python lecture 12

Iterator Protocol

● Iterators are objects that allow us to iterate over other objects one item at a time (e.g., iterate over values in a range, over lines in a file, over nodes in a tree, over records in a database)

● In principle, any Python object can be turned into an iterator so long as it implements the Iterator Protocol

Page 5: Python lecture 12

Iterator Protocol

● In Python 2.7, the Iterator Protocol consists of two methods __iter__ and next()

● __iter__ returns the iterator object (typically self) that implements the next() method

● The next() method on first call returns the first element, on the second call – the second element, etc

● When there are no more elements a call to next() should raise a StopIteration exception

Page 6: Python lecture 12

Define an iterator over prime numbers.

Page 7: Python lecture 12

Built-in iter() Function● If you know that a Python object is iterable, you can use the built-

in function iter() to obtain an iterator for that object>>> lstit = iter([1, 2, 3, 4])

>>> lstit.next()

1

>>> lstit.next()

2

>>> strit = iter('abcd efg')

>>> strit.next()

'a'

Page 8: Python lecture 12

Factory Design Pattern

Page 9: Python lecture 12

Design Patterns● In OOP, design patterns are referred to

standardized ways of capturing specify types of behavior

● Design patterns typically evolve bottom-up: after repeating the same task for a few times, a software engineer or a team of software engineers may notice a sequence of actions that may be worth reusing – and a design pattern is born

Page 10: Python lecture 12

Factory Design Pattern● Factory is an OOP design pattern that

generalizes the constructor concept● In some circumstances, it is conceptually easier or

more efficient to create a class whose objects produce other types of objects

● A factory class has a method for constructing each type of object it is designed to construct

Page 11: Python lecture 12

Generators

Page 12: Python lecture 12

Generators

● A generator is a lazy function that remembers its state from call to call

● A lazy function returns (or, in Python terminology, yields) its values one at a time without giving up control

● Generators are typically used for handling really large ranges or solving combinatorial optimization problems

Page 13: Python lecture 12

Definition● Let us use this definition: a generator is an object that

iterates over some data in a lazy fashion● This definition has several implications:

Generators are iterators Generators are associated with specific data Generators are lazy: they yield data items one at a

time and without necessarily storing all data items in memory

Page 14: Python lecture 12

Generator Construction● In Python, there are two ways to construct

generators: generator factories and generator comprehensions (generator expressions)

● Generator factories are used when more complex generators are required

● Generator comprehensions are used for simpler generators

Page 15: Python lecture 12

Generator Factories

Page 16: Python lecture 12

Generator Factories

def gen_factory_1234():

yield 1

yield 2

yield 3

yield 4

● Every Python function that has the keyword yield in its body defines a generator factory

● For example:

Page 17: Python lecture 12

Generator Factories

>>> g1 = gen_factory_123()

>>> g1.next()

1

>>> g1.next()

2

>>> g1.next()

3

>>> g1.next()

4

>>> g1.next()

StopIteration Exception

● Why is gen_factory_1234 a generator factory?● Because on each invocation it creates a new object

Page 18: Python lecture 12

Generator Objects

● Unlike functions that return values, generators yield values and remember the point at which the last value is yielded

● On the next invocation, a generator pick up from the point at which the previous value was yielded

● When there are no more values to yield, StopIteration is raised

Page 19: Python lecture 12

Generator Factories

def gen_factory_range(lower, upper):

for i in xrange(lower, upper+1):

yield i

● Here is a more generic way of defining a generator factory that yields each number in a range

Page 20: Python lecture 12

Generator Objects● Generator objects are one-time only: once a

generator object goes over its data (if the number of data items is finite), it cannot be restarted

● You can create as many generator objects coupled to the same data as you want

● Generator objects can be consumed by standard Python sequence constructors or sequence processors

Page 21: Python lecture 12

Examples## two generators defined over the same data

>>> gfr1 = gen_factory_range(10, 15)

>>> gfr2 = gen_factory_range(10, 15)

## two generator objects consumed by zip constructor

>>> zip(gfr1, gfr2)

[(10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15)]

>>> gfr3 = gen_factory_range(10, 15)

## generator object consumed by list constructor

>>> list(gfr3)

[10, 11, 12, 13, 14, 15]

## generator object consumed by sum

>>> sum(gen_factory_range(1, 5))

15

Page 22: Python lecture 12

Examples## generator object consumed by max

>>> max(gen_factory_range(1, 5))

5

## generator object consumed by set constructor

>>> set(gen_factory_range(1, 5))

set([1, 2, 3, 4, 5])

## generator object used by the boolean in operator

>>> 5 in gen_factory_range(1, 5)

True

Page 23: Python lecture 12

Examples## generator factory of Fibonacci number generators

def gen_fib():

prev, curr = 0, 1

yield prev

yield curr

while True:

nxt = prev + curr

yield nxt

prev, curr = curr, nxt

Page 24: Python lecture 12

Generator Comprehension● The most straightforward method of obtaining a generator is through

generator comprehensions (aka generator expressions)● Generator comprehension is similar to list comprehension except it

uses parentheses around generator expressions and it does not enumerate all elements in the range

>>> g1 = (x**3 for x in xrange(1, 100001))

>>> g1.next()

1

>>> g1.next()

8

>>> g2 = (i**2+10 for i in xrange(1, 100001))

>>> g2.next()

11

Page 25: Python lecture 12

PIL Basics

Page 26: Python lecture 12

Creating New Images● Image.new(mode, size [, color])

● The mode of an image describes the way it represents colors

'1' : Black and white (monochrome), one bit per pixel. 'L' : Gray scale, one 8-bit byte per pixel. 'RGB' : True red-green-blue color, three bytes per pixel.

● size is a tuple (width, height)

● color is optional

If missing, the new image is filled with black If present, the new image is filled with that color

Page 27: Python lecture 12

Creating and Saving Images>>> import Image

>>> im1 = Image.new('1', (100, 50))

>>> im1.save("C:\\Python27\\CS3430\\img\\first.BMP")

>>> im2 = Image.new('L', (100, 50), 'white')

>>> im2.save("C:\\Python27\\CS3430\\img\\second.BMP")

>>> im3 = Image.new("RGB", (100, 50), (0, 0, 255))

>>> im3.save("C:\\Python27\\CS3430\\img\\third.BMP")

Page 28: Python lecture 12

PIL Coordinates0,0 x

y

Example:im = Image.new('L', (100, 50), 255)## im's x ranges from 0 to 99## im's y ranges from 0 to 49

Page 29: Python lecture 12

Getting Pixel Values● im.getpixel((x,y))

## im is an Image object

## x,y is a tuple (x, y)

● (0, 0) is the top left corner

● Example:

>>> im = Image.new("RGB", (100, 50), (0, 0, 255))

>>> im.getpixel((0, 0))

Page 30: Python lecture 12

Setting Pixel Values

● im.setpixel((x, y), color)

## im is an Image object

## x,y is a tuple (x, y)● color is a mode-dependent color spec

Page 31: Python lecture 12

Reading Images from Files## 1. Create an image

>>> im1 = Image.new('RGB', (100, 100), (0, 255, 0))

## 2. Save an image

>>> im1.save('/home/user/Pictures/im1.bmp')

## 3. Open an image from an existing file

>>> im2 = Image.open('/home/user/Pictures/im1.bmp')

>>> print im2.format, im2.size, im2.mode

BMP (100, 100) RGB

Page 32: Python lecture 12

Colors in PIL● Colors depend on the mode of the image● In RGB mode, colors are returned as 3-tuples (red,

green, blue)

● Values range from 0 upto 255

● Common colors can set with string values, e.g., 'white', 'black', 'red'

Page 33: Python lecture 12

Draw a circle using putpixel()

Page 34: Python lecture 12

Drawing● It is possible to use putpixel() to draw various figures

but this can get tedious and error-prone● ImageDraw is used to draw simple 2D graphics:

Lines Ellipses Text

Page 35: Python lecture 12

Using ImageDraw● First, create an Image object:

Image.new() or Image.open()

● Second, create an ImageDraw object from the Image object: import Image

import ImageDraw

im = Image.new('RGB', (100, 100))

Draw = ImageDraw.Draw(im)

● Third, use the ImageDraw object to draw various figures in the Image

● Fourth, save the Image in a file if necessary

Page 36: Python lecture 12

Draw.line()

>>> draw.line(xy, options)● Draws a line between the coordinates in the xy list.● The coordinate list can be any sequence object

containing either 2-tuples [ (x, y), … ] or numeric values [ x, y, … ]. It should contain at least two coordinates.

● The fill option gives the color to use for the line.

Page 37: Python lecture 12

PIL Reading● Overviewhttp://www.pythonware.com/library/pil/handbook/overview.htm

● Tutorial:http://www.pythonware.com/library/pil/handbook/introduction.htm

● Concepts:http://www.pythonware.com/library/pil/handbook/concepts.htm

● http://effbot.org/imagingbook/imagedraw.htm

Page 38: Python lecture 12

Reading & References● www.python.org● Ch 09 M. L. Hetland. Beginning Python From Novice to Pro-

fessional, 2nd Ed., APRESS