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

What's hot (20)

PPTX
Java Arrays and DateTime Functions
Jamsher bhanbhro
 
PPTX
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Meghaj Mallick
 
PPTX
Stack Data structure
B Liyanage Asanka
 
PDF
An Introduction to the C++ Standard Library
Joyjit Choudhury
 
PPT
List in java
nitin kumar
 
PDF
Algorithms: II
Joyjit Choudhury
 
PPT
2CPP16 - STL
Michael Heron
 
PPTX
Function overloading
Sudeshna Biswas
 
PPTX
Understanding the components of standard template library
Rahul Sharma
 
PPTX
Queues
Syed Zaid Irshad
 
PPTX
Functions with heap and stack
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Grid search (parameter tuning)
Akhilesh Joshi
 
PPTX
Ppt presentation of queues
Buxoo Abdullah
 
PPT
Stacks
FarithaRiyaz
 
PDF
Python - Lecture 12
Ravi Kiran Khareedi
 
PPTX
Data Analysis packages
Devashish Kumar
 
PDF
Python standard data types
Learnbay Datascience
 
PPT
Lists
Sumit Tambe
 
Java Arrays and DateTime Functions
Jamsher bhanbhro
 
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Meghaj Mallick
 
Stack Data structure
B Liyanage Asanka
 
An Introduction to the C++ Standard Library
Joyjit Choudhury
 
List in java
nitin kumar
 
Algorithms: II
Joyjit Choudhury
 
2CPP16 - STL
Michael Heron
 
Function overloading
Sudeshna Biswas
 
Understanding the components of standard template library
Rahul Sharma
 
Grid search (parameter tuning)
Akhilesh Joshi
 
Ppt presentation of queues
Buxoo Abdullah
 
Stacks
FarithaRiyaz
 
Python - Lecture 12
Ravi Kiran Khareedi
 
Data Analysis packages
Devashish Kumar
 
Python standard data types
Learnbay Datascience
 

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

KEY
Programming with Python - Week 3
Ahmet Bulut
 
PPTX
Advance python
pulkit agrawal
 
PPTX
Python for Data Science function third module ppt.pptx
bmit1
 
PDF
Introduction to Functional Programming
Francesco Bruni
 
PPTX
Programming in C sesion 2
Prerna Sharma
 
PPTX
Python Learn Function with example programs
GeethaPanneer
 
PPTX
Pythonlearn-04-Functions (1).pptx
leavatin
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Iterarators and generators in python
Sarfaraz Ghanta
 
PDF
Advanced features of Lisp functions Advanced features of Lisp functions
CvDs3
 
PPT
Function
yash patel
 
PPTX
Functions_new.pptx
Yagna15
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
Inline Functions and Default arguments
Nikhil Pandit
 
PPTX
Functional Programming in Swift
Saugat Gautam
 
PPTX
Function in C++, Methods in C++ coding programming
estorebackupr
 
PPTX
python ppt.pptx
MONAR11
 
PPTX
L 5 Numpy final learning and Coding
Kirti Verma
 
PDF
Functions-.pdf
arvdexamsection
 
PPTX
Generators-in-Python-for-Developers.pptx
Ganesh Bhosale
 
Programming with Python - Week 3
Ahmet Bulut
 
Advance python
pulkit agrawal
 
Python for Data Science function third module ppt.pptx
bmit1
 
Introduction to Functional Programming
Francesco Bruni
 
Programming in C sesion 2
Prerna Sharma
 
Python Learn Function with example programs
GeethaPanneer
 
Pythonlearn-04-Functions (1).pptx
leavatin
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Iterarators and generators in python
Sarfaraz Ghanta
 
Advanced features of Lisp functions Advanced features of Lisp functions
CvDs3
 
Function
yash patel
 
Functions_new.pptx
Yagna15
 
Python functions
Prof. Dr. K. Adisesha
 
Inline Functions and Default arguments
Nikhil Pandit
 
Functional Programming in Swift
Saugat Gautam
 
Function in C++, Methods in C++ coding programming
estorebackupr
 
python ppt.pptx
MONAR11
 
L 5 Numpy final learning and Coding
Kirti Verma
 
Functions-.pdf
arvdexamsection
 
Generators-in-Python-for-Developers.pptx
Ganesh Bhosale
 
Ad

More from John(Qiang) Zhang (8)

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

Recently uploaded (20)

PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 

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.