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)

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

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

Python lecture 05
Python lecture 05
Tanwir Zaman
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Python Training
Python Training
TIB Academy
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Python cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
Functions, List and String methods
Functions, List and String methods
PranavSB
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
A tour of Python
A tour of Python
Aleksandar Veselinovic
 
An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Functions in python
Functions in python
Ilian Iliev
 
python.pdf
python.pdf
wekarep985
 
justbasics.pdf
justbasics.pdf
DrRajkumarKhatri
 
Python Programming Module 3 (2).pdf
Python Programming Module 3 (2).pdf
Thanmayee S
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
python language programming presentation
python language programming presentation
lbisht2
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Python cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
Functions, List and String methods
Functions, List and String methods
PranavSB
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Functions in python
Functions in python
Ilian Iliev
 
Python Programming Module 3 (2).pdf
Python Programming Module 3 (2).pdf
Thanmayee S
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
python language programming presentation
python language programming presentation
lbisht2
 
Ad

More from John(Qiang) Zhang (8)

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

Recently uploaded (20)

Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 

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.