SlideShare a Scribd company logo
1 of 38
Download to read offline
Python & Perl
Lecture 12
Department of Computer Science
Utah State University
Outline
●

Iterators

●

Generators

●

PIL Basics
Iterators
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
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
Define an iterator over prime numbers.
Built-in iter() Function
●

If you know that a Python object is iterable, you can use the builtin 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'
Factory Design Pattern
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
Factory Design Pattern
●

●

●

Factory is an OOP design pattern
generalizes the constructor concept

that

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
Generators
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
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
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
Generator Factories
Generator Factories
●

●

Every Python function that has the keyword yield
in its body defines a generator factory
For example:
def gen_factory_1234():
yield 1
yield 2
yield 3
yield 4
Generator Factories
●

Why is gen_factory_1234 a generator factory?

●

Because on each invocation it creates a new object
>>> g1 = gen_factory_123()
>>> g1.next()
1
>>> g1.next()
2
>>> g1.next()
3
>>> g1.next()
4
>>> g1.next()
StopIteration Exception
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
Generator Factories
●

Here is a more generic way of defining a generator
factory that yields each number in a range
def gen_factory_range(lower, upper):
for i in xrange(lower, upper+1):
yield i
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
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
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
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
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
PIL Basics
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
Creating and Saving Images
>>> import Image
>>> im1 = Image.new('1', (100, 50))
>>> im1.save("C:Python27CS3430imgfirst.BMP")
>>> im2 = Image.new('L', (100, 50), 'white')
>>>
im2.save("C:Python27CS3430imgsecond.BMP")
>>> im3 = Image.new("RGB", (100, 50), (0, 0, 255))
>>>
im3.save("C:Python27CS3430imgthird.BMP")
0,0

PIL Coordinates
x

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

y
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))
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
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
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'
Draw a circle using putpixel()
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
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
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.
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
Reading & References
●
●

www.python.org
Ch 09 M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS

More Related Content

What's hot

Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1Jatin Miglani
 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning LiveMike Anderson
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESAniruddha Paul
 
Stack and heap allocation
Stack and heap allocationStack and heap allocation
Stack and heap allocationankitbhasin23
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonCP-Union
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queueecomputernotes
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisSilvio Cesare
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonAndrew Ferlitsch
 
Kernels in convolution
Kernels in convolutionKernels in convolution
Kernels in convolutionRevanth Kumar
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowAndrew Ferlitsch
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITiansAshish Bansal
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 

What's hot (20)

Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1
 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning Live
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
 
NUMPY
NUMPY NUMPY
NUMPY
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Stack and heap allocation
Stack and heap allocationStack and heap allocation
Stack and heap allocation
 
Performance
PerformancePerformance
Performance
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
 
Introduction to numpy
Introduction to numpyIntroduction to numpy
Introduction to numpy
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
 
Data structures
Data structuresData structures
Data structures
 
Kernels in convolution
Kernels in convolutionKernels in convolution
Kernels in convolution
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to Tensorflow
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITians
 
Welcome to python
Welcome to pythonWelcome to python
Welcome to python
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Google TensorFlow Tutorial
Google TensorFlow TutorialGoogle TensorFlow Tutorial
Google TensorFlow Tutorial
 

Similar to Python lecture 12

python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptxMONAR11
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
could you draw uml diagram for this code from PIL import Image, Im.pdf
could you draw uml diagram for this code from PIL import Image, Im.pdfcould you draw uml diagram for this code from PIL import Image, Im.pdf
could you draw uml diagram for this code from PIL import Image, Im.pdfmurtuzadahadwala3
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlabAman Gupta
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor John(Qiang) Zhang
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and ModulesRaginiJain21
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaFerdinand Jamitzky
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Ganesan Narayanasamy
 
Computer graphics
Computer graphics Computer graphics
Computer graphics shafiq sangi
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.Mosky Liu
 
Machine learning Experiments report
Machine learning Experiments report Machine learning Experiments report
Machine learning Experiments report AlmkdadAli
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxRameshMishra84
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e práticaPET Computação
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfoptimusnotch44
 
Introduction to the Stat-JR software package
Introduction to the Stat-JR software packageIntroduction to the Stat-JR software package
Introduction to the Stat-JR software packageUniversity of Southampton
 
Image processing using matlab
Image processing using matlabImage processing using matlab
Image processing using matlabdedik dafiyanto
 

Similar to Python lecture 12 (20)

Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Algorithms.
Algorithms. Algorithms.
Algorithms.
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
could you draw uml diagram for this code from PIL import Image, Im.pdf
could you draw uml diagram for this code from PIL import Image, Im.pdfcould you draw uml diagram for this code from PIL import Image, Im.pdf
could you draw uml diagram for this code from PIL import Image, Im.pdf
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlab
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cuda
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
Machine learning Experiments report
Machine learning Experiments report Machine learning Experiments report
Machine learning Experiments report
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docx
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e prática
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdf
 
Introduction to the Stat-JR software package
Introduction to the Stat-JR software packageIntroduction to the Stat-JR software package
Introduction to the Stat-JR software package
 
Image processing using matlab
Image processing using matlabImage processing using matlab
Image processing using matlab
 

More from Tanwir Zaman

More from Tanwir Zaman (15)

Cs3430 lecture 17
Cs3430 lecture 17Cs3430 lecture 17
Cs3430 lecture 17
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
Python lecture 10
Python lecture 10Python lecture 10
Python lecture 10
 
Python lecture 09
Python lecture 09Python lecture 09
Python lecture 09
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
Python lecture 07
Python lecture 07Python lecture 07
Python lecture 07
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Python lecture 01
Python lecture 01Python lecture 01
Python lecture 01
 
Python lecture 11
Python lecture 11Python lecture 11
Python lecture 11
 

Recently uploaded

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 

Recently uploaded (20)

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 

Python lecture 12

  • 1. Python & Perl Lecture 12 Department of Computer Science Utah State University
  • 4. 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
  • 5. 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
  • 6. Define an iterator over prime numbers.
  • 7. Built-in iter() Function ● If you know that a Python object is iterable, you can use the builtin 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'
  • 9. 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
  • 10. Factory Design Pattern ● ● ● Factory is an OOP design pattern generalizes the constructor concept that 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
  • 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
  • 13. 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
  • 14. 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
  • 16. Generator Factories ● ● Every Python function that has the keyword yield in its body defines a generator factory For example: def gen_factory_1234(): yield 1 yield 2 yield 3 yield 4
  • 17. Generator Factories ● Why is gen_factory_1234 a generator factory? ● Because on each invocation it creates a new object >>> g1 = gen_factory_123() >>> g1.next() 1 >>> g1.next() 2 >>> g1.next() 3 >>> g1.next() 4 >>> g1.next() StopIteration Exception
  • 18. 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
  • 19. Generator Factories ● Here is a more generic way of defining a generator factory that yields each number in a range def gen_factory_range(lower, upper): for i in xrange(lower, upper+1): yield i
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 26. 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
  • 27. Creating and Saving Images >>> import Image >>> im1 = Image.new('1', (100, 50)) >>> im1.save("C:Python27CS3430imgfirst.BMP") >>> im2 = Image.new('L', (100, 50), 'white') >>> im2.save("C:Python27CS3430imgsecond.BMP") >>> im3 = Image.new("RGB", (100, 50), (0, 0, 255)) >>> im3.save("C:Python27CS3430imgthird.BMP")
  • 28. 0,0 PIL Coordinates x Example: im = Image.new('L', (100, 50), 255) ## im's x ranges from 0 to 99 ## im's y ranges from 0 to 49 y
  • 29. 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))
  • 30. 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
  • 31. 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
  • 32. 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'
  • 33. Draw a circle using putpixel()
  • 34. 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
  • 35. 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
  • 36. 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.
  • 38. Reading & References ● ● www.python.org Ch 09 M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS