SlideShare a Scribd company logo
THE PYTHON STD LIB BY
EXAMPLE – ALGORITHM
John
Saturday, December 21, 2013
Brief introduction
• Python includes several modules which can
implement algorithm elegantly and concisely.
• It support uprely procedural, OOP and
functional styles.
• It includes: functools, partial , itertools,
operator, contextlib etc
FUNCTOOLS –TOOLS FOR MANIPULATING
FUNCTIONS
Partial Objects: provide default
argument
• The partial objects can provide or change the default
value of the argument.
• Example code (assume we have define function
myfunc(a,b=1) :
>>> import functools
>>> p1 = functools.partial(myfunc,b=4)
>>> p1(‘passing a’)
>>> p2 = functools.partial(myfunc,’default a’,b=99)
>>> p2()
>>> p2(b=‘override b’)
Function update_wrapper()
• The partial object does not have __name__
and __doc__ attributes by default.
• Using update_wrapper(0 copies or added
attributes from the original function.
Format:
>>> functools.update_wrapper(p1,myfunc)
the “rich comparison”
First let us learn which is “rich comparion” in
python.
•Rich comparison method API (__lt__, __le__,
__eq__, __gt__, __ge__)
(Here le means less than, le means “less or equal”,
gt means “greater than”, ge means “greater than
or equal”)
•These method API can help perform a single
comparison operation and return a Boolean value
Example of rich comparision
We implement __eq__ and __gt__.
Functools.total_ordering can implement other
operator (<, <=, >= etc) base on eq and gt.
Function cmp_to_key: convert
cmp to key for sorting
• In Python 2.xx, cmp do comparion:
cmp(2,1) -> 1
cmp(1,1) -> 0
cmp(1,2) -> -1
• In python 3, cmp in sort function no longer
supported.
• Functools.cmp_to_key convert cmp to key
for sorting
Quick example of cmp_to_key
• Built-in funtion cmp need two argument.
• Sorted function can use other option
key=func. Sorted by key (only support this on
Python 3.X)
ITERTOOLSITERATOR
FUNCTIONS
Brief introduction
• The itertools module includes a set of
functions for working with sequence data
sets (list, tuple,set,dict etc).
• Iterator based code offer better memory
comsumption.
Function chain(): Merge iterators
• Take serveral iterators as arguments and
return a single iterator
Function imap: similar as map
• Imap accept a function, and multiple
sequences, return a tuple.
Other function merge and split
iterators
• Function izip: like zip, but combine iterator
and return iterator of tuple instead of list
• Function islice: similar as slice
• Function imap: similar as map
• Function ifilter: similar as filter, filter those
items test functions return True
• Function ifilterfalse: filter those items where
the test function return False
Function starmap:
• First, let us review the star * syntax in Python.
• Star * means unpack the sequence reference as
argument list.
>>> def foo(bar,lee):
print bar,lee
>>> a = [1,2]
>>> foo(a) # it is wrong, need two arguments
>>> foo(*a) # it is right. The list is unpack
>>>foo(1,2) # it is the same thing
Function starmap: unpack the
input
• Unpack the item as argument using the *
syntax
Function count(): iterator produce
consecutive integers
• Function count(start=0,step=1): user can pass
the start and step value.No upper bound
argument.
>>> a = itertools.count(start=10,step=10)
>>> for i in a:
print I
if I >100:
break

Print list 10,20,30 … 110
Function cycle: iterator do
indefinitely repeats
• It need remember the whole input, so it may
consume quite a bit memo if input iterator is
long.
Function repeat: repeat same
value several time
• This example mean repeat ‘a’ 5 times.
>>> itertools.repeat(‘a’, 5)
It is similar as list [‘a’,’a’.’a’,’a’,’a’]
The return is a iterator but not list. So it use the
memo only when it is called.
Function dropwhile and takewhile
• Func dropwhile start output while condition
become false for the first time
• Example, 3rd element do not met x<1. So it
return 3 to end of this list
Function dropwhile and takewhile
• The opposite of dropwhile: stop output while
condition become false for the first time
• So all output items meet the condition
function.

More Related Content

PPT
Python advanced 3.the python std lib by example –data structures
PPT
Python advanced 3.the python std lib by example – application building blocks
PDF
Lec16-CS110 Computational Engineering
PPT
Python advanced 1.handle error, generator, decorator and decriptor
PDF
Algorithms: I
PPT
Review functions
PDF
Priority Queue
PDF
Stack & Queue
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example – application building blocks
Lec16-CS110 Computational Engineering
Python advanced 1.handle error, generator, decorator and decriptor
Algorithms: I
Review functions
Priority Queue
Stack & Queue

What's hot (20)

PPTX
Java Arrays and DateTime Functions
PPTX
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
PPTX
Stack Data structure
PDF
An Introduction to the C++ Standard Library
PPT
List in java
PDF
Algorithms: II
PPT
2CPP16 - STL
PPTX
Function overloading
PPTX
Understanding the components of standard template library
PPTX
PPTX
PPTX
Grid search (parameter tuning)
PPTX
Ppt presentation of queues
PPT
Stacks
PDF
Python - Lecture 12
PPTX
Data Analysis packages
PDF
Python standard data types
PPT
Java Arrays and DateTime Functions
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Stack Data structure
An Introduction to the C++ Standard Library
List in java
Algorithms: II
2CPP16 - STL
Function overloading
Understanding the components of standard template library
Grid search (parameter tuning)
Ppt presentation of queues
Stacks
Python - Lecture 12
Data Analysis packages
Python standard data types
Ad

Similar to Python advanced 3.the python std lib by example – algorithm (20)

KEY
Programming with Python - Week 3
PPTX
Advance python
PPTX
Python for Data Science function third module ppt.pptx
PDF
Introduction to Functional Programming
PPTX
Programming in C sesion 2
PPTX
Python Learn Function with example programs
PPTX
Pythonlearn-04-Functions (1).pptx
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
Iterarators and generators in python
PDF
Advanced features of Lisp functions Advanced features of Lisp functions
PPT
Function
PPTX
Tuples in pyhton programming using simple codes.pptx
PPTX
Functions_new.pptx
PDF
Python functions
PPTX
Inline Functions and Default arguments
PPTX
Functional Programming in Swift
PPTX
Function in C++, Methods in C++ coding programming
PPTX
python ppt.pptx
PPTX
L 5 Numpy final learning and Coding
PDF
Functions-.pdf
Programming with Python - Week 3
Advance python
Python for Data Science function third module ppt.pptx
Introduction to Functional Programming
Programming in C sesion 2
Python Learn Function with example programs
Pythonlearn-04-Functions (1).pptx
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
Iterarators and generators in python
Advanced features of Lisp functions Advanced features of Lisp functions
Function
Tuples in pyhton programming using simple codes.pptx
Functions_new.pptx
Python functions
Inline Functions and Default arguments
Functional Programming in Swift
Function in C++, Methods in C++ coding programming
python ppt.pptx
L 5 Numpy final learning and Coding
Functions-.pdf
Ad

More from John(Qiang) Zhang (8)

PPTX
Git and github introduction
PPT
Python testing
PPT
Profiling in python
PPT
Introduction to jython
PPT
Introduction to cython
PPT
A useful tools in windows py2exe(optional)
PPT
Python advanced 3.the python std lib by example – system related modules
PPTX
Python advanced 2. regular expression in python
Git and github introduction
Python testing
Profiling in python
Introduction to jython
Introduction to cython
A useful tools in windows py2exe(optional)
Python advanced 3.the python std lib by example – system related modules
Python advanced 2. regular expression in python

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Spectroscopy.pptx food analysis technology
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Encapsulation theory and applications.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
sap open course for s4hana steps from ECC to s4
A comparative analysis of optical character recognition models for extracting...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Programs and apps: productivity, graphics, security and other tools
Spectroscopy.pptx food analysis technology
gpt5_lecture_notes_comprehensive_20250812015547.pdf
cuic standard and advanced reporting.pdf
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Dropbox Q2 2025 Financial Results & Investor Presentation
Assigned Numbers - 2025 - Bluetooth® Document
Encapsulation theory and applications.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
sap open course for s4hana steps from ECC to s4

Python advanced 3.the python std lib by example – algorithm

  • 1. THE PYTHON STD LIB BY EXAMPLE – ALGORITHM John Saturday, December 21, 2013
  • 2. Brief introduction • Python includes several modules which can implement algorithm elegantly and concisely. • It support uprely procedural, OOP and functional styles. • It includes: functools, partial , itertools, operator, contextlib etc
  • 3. FUNCTOOLS –TOOLS FOR MANIPULATING FUNCTIONS
  • 4. Partial Objects: provide default argument • The partial objects can provide or change the default value of the argument. • Example code (assume we have define function myfunc(a,b=1) : >>> import functools >>> p1 = functools.partial(myfunc,b=4) >>> p1(‘passing a’) >>> p2 = functools.partial(myfunc,’default a’,b=99) >>> p2() >>> p2(b=‘override b’)
  • 5. Function update_wrapper() • The partial object does not have __name__ and __doc__ attributes by default. • Using update_wrapper(0 copies or added attributes from the original function. Format: >>> functools.update_wrapper(p1,myfunc)
  • 6. the “rich comparison” First let us learn which is “rich comparion” in python. •Rich comparison method API (__lt__, __le__, __eq__, __gt__, __ge__) (Here le means less than, le means “less or equal”, gt means “greater than”, ge means “greater than or equal”) •These method API can help perform a single comparison operation and return a Boolean value
  • 7. Example of rich comparision We implement __eq__ and __gt__. Functools.total_ordering can implement other operator (<, <=, >= etc) base on eq and gt.
  • 8. Function cmp_to_key: convert cmp to key for sorting • In Python 2.xx, cmp do comparion: cmp(2,1) -> 1 cmp(1,1) -> 0 cmp(1,2) -> -1 • In python 3, cmp in sort function no longer supported. • Functools.cmp_to_key convert cmp to key for sorting
  • 9. Quick example of cmp_to_key • Built-in funtion cmp need two argument. • Sorted function can use other option key=func. Sorted by key (only support this on Python 3.X)
  • 11. Brief introduction • The itertools module includes a set of functions for working with sequence data sets (list, tuple,set,dict etc). • Iterator based code offer better memory comsumption.
  • 12. Function chain(): Merge iterators • Take serveral iterators as arguments and return a single iterator
  • 13. Function imap: similar as map • Imap accept a function, and multiple sequences, return a tuple.
  • 14. Other function merge and split iterators • Function izip: like zip, but combine iterator and return iterator of tuple instead of list • Function islice: similar as slice • Function imap: similar as map • Function ifilter: similar as filter, filter those items test functions return True • Function ifilterfalse: filter those items where the test function return False
  • 15. Function starmap: • First, let us review the star * syntax in Python. • Star * means unpack the sequence reference as argument list. >>> def foo(bar,lee): print bar,lee >>> a = [1,2] >>> foo(a) # it is wrong, need two arguments >>> foo(*a) # it is right. The list is unpack >>>foo(1,2) # it is the same thing
  • 16. Function starmap: unpack the input • Unpack the item as argument using the * syntax
  • 17. Function count(): iterator produce consecutive integers • Function count(start=0,step=1): user can pass the start and step value.No upper bound argument. >>> a = itertools.count(start=10,step=10) >>> for i in a: print I if I >100: break Print list 10,20,30 … 110
  • 18. Function cycle: iterator do indefinitely repeats • It need remember the whole input, so it may consume quite a bit memo if input iterator is long.
  • 19. Function repeat: repeat same value several time • This example mean repeat ‘a’ 5 times. >>> itertools.repeat(‘a’, 5) It is similar as list [‘a’,’a’.’a’,’a’,’a’] The return is a iterator but not list. So it use the memo only when it is called.
  • 20. Function dropwhile and takewhile • Func dropwhile start output while condition become false for the first time • Example, 3rd element do not met x<1. So it return 3 to end of this list
  • 21. Function dropwhile and takewhile • The opposite of dropwhile: stop output while condition become false for the first time • So all output items meet the condition function.