Programming in Python
A Two Day Workshop
Satyaki Sikdar
Vice Chair
ACM Student Chapter
Heritage Institute of Technology
April 22 2016
Satyaki Sikdar© Programming in Python April 22 2016 1 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro whoami
whoami
Extremely lazy
Coding in Python since the summer of 2013 - not an expert by any means
An average programmer at best. Comfortable writing 750 - 1000 lines of code
In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and
professional
I love Python - duh!
Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha
Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time!
Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
great expectations
Things you can expect from me
Clarity
No spoon feeding
Desperate attempts at making jokes
Things I expect from you
An open mind
Patience - not everything would make perfect sense at first
Attention - especially to details
Cooperation - it’s going to be a long haul
Interruptions - feel free to stop me to ask relevant questions
Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
hour 0: intro expectations and takeaways
your takeaways
1 A degree of fluency in reading and writing short - medium Python codes
2 A knowledge of how things work in Python and why certain things are done in a certain
way
3 Learning something exciting - might not be only Python
4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS
Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
hour 0: intro expectations and takeaways
your takeaways
1 A degree of fluency in reading and writing short - medium Python codes
2 A knowledge of how things work in Python and why certain things are done in a certain
way
3 Learning something exciting - might not be only Python
4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS
Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
hour 0: intro expectations and takeaways
your takeaways
1 A degree of fluency in reading and writing short - medium Python codes
2 A knowledge of how things work in Python and why certain things are done in a certain
way
3 Learning something exciting - might not be only Python
4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS
Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
hour 0: intro expectations and takeaways
your takeaways
1 A degree of fluency in reading and writing short - medium Python codes
2 A knowledge of how things work in Python and why certain things are done in a certain
way
3 Learning something exciting - might not be only Python
4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS
Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
hour 0: intro lesson plan
the lesson plan for day I
hour topic
1 introduction, motivation, Guido, awesomeness of Python
2 playing around with the interpreter - variables, simple data types
3 predefined functions, conditionals, lists, loops
4 tuples, user defined functions, basic recursion
5 sets, dictionaries, errors and exceptions, intro to OOP
6 OOP - inheritance, applying OOP
Satyaki Sikdar© Programming in Python April 22 2016 5 / 137
hour 0: intro Guido
Maester Guido van Rossum
The Dutch are known for their easygoing nature. And Guido is no different.
Figure: Guido van Rossum
Born: 31 January, 1956 in Haarlem, The Netherlands
Studied Computer Science from the University of Amsterdam
Started Python as a hobby project in 1989. It grew into a
new language in a couple of years.
Recognized as a Distinguished Engineer by ACM
Xoogler and now works for Dropbox
Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
hour 0: intro Guido
Maester Guido van Rossum
The Dutch are known for their easygoing nature. And Guido is no different.
Figure: Guido van Rossum
Born: 31 January, 1956 in Haarlem, The Netherlands
Studied Computer Science from the University of Amsterdam
Started Python as a hobby project in 1989. It grew into a
new language in a couple of years.
Recognized as a Distinguished Engineer by ACM
Xoogler and now works for Dropbox
Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
hour 0: intro Guido
Maester Guido van Rossum
The Dutch are known for their easygoing nature. And Guido is no different.
Figure: Guido van Rossum
Born: 31 January, 1956 in Haarlem, The Netherlands
Studied Computer Science from the University of Amsterdam
Started Python as a hobby project in 1989. It grew into a
new language in a couple of years.
Recognized as a Distinguished Engineer by ACM
Xoogler and now works for Dropbox
Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
hour 0: intro Guido
Maester Guido van Rossum
The Dutch are known for their easygoing nature. And Guido is no different.
Figure: Guido van Rossum
Born: 31 January, 1956 in Haarlem, The Netherlands
Studied Computer Science from the University of Amsterdam
Started Python as a hobby project in 1989. It grew into a
new language in a couple of years.
Recognized as a Distinguished Engineer by ACM
Xoogler and now works for Dropbox
Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
hour 0: intro Guido
Maester Guido van Rossum
The Dutch are known for their easygoing nature. And Guido is no different.
Figure: Guido van Rossum
Born: 31 January, 1956 in Haarlem, The Netherlands
Studied Computer Science from the University of Amsterdam
Started Python as a hobby project in 1989. It grew into a
new language in a couple of years.
Recognized as a Distinguished Engineer by ACM
Xoogler and now works for Dropbox
Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
hour 0: intro popularity
it’s good to be popular
It’s true for people and programming languages alike
Tons of resources to get help from if you are stuck
You’ll get a lot of people to collaborate
Employment opportunities open up
Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
hour 0: intro popularity
it’s good to be popular
It’s true for people and programming languages alike
Tons of resources to get help from if you are stuck
You’ll get a lot of people to collaborate
Employment opportunities open up
Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
hour 0: intro popularity
it’s good to be popular
It’s true for people and programming languages alike
Tons of resources to get help from if you are stuck
You’ll get a lot of people to collaborate
Employment opportunities open up
Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
hour 0: intro popularity
it’s good to be popular
It’s true for people and programming languages alike
Tons of resources to get help from if you are stuck
You’ll get a lot of people to collaborate
Employment opportunities open up
Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
hour 0: intro popularity
popularity of Python
©codeeval - hiring demand trends
Satyaki Sikdar© Programming in Python April 22 2016 8 / 137
hour 0: intro popularity
popularity of Python
©PYPL
Satyaki Sikdar© Programming in Python April 22 2016 9 / 137
hour 0: intro popularity
popularity of Python
Satyaki Sikdar© Programming in Python April 22 2016 10 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
what makes Py Awesome?
Open source license - right from the early days
Very versatile
The Zen of Python - you should read it every now and then
A strong and active community
PyPI - the modules repository has over 30, 000 user created modules for ready use
Killer apps like Django and Pandas
Lots and lots of reference materials available including books, video lectures and tutorials
Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
hour 0: intro awesomeness of Python
the awesomeness continues!
Ease of learning - you’ll see it soon
Very teachable - low syntax overhead
Rapid development cycle - easy to express yourself
Readable, beautiful and brevity - you’ll love to code
Interactive prompt
Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
hour 0: intro awesomeness of Python
the awesomeness continues!
Ease of learning - you’ll see it soon
Very teachable - low syntax overhead
Rapid development cycle - easy to express yourself
Readable, beautiful and brevity - you’ll love to code
Interactive prompt
Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
hour 0: intro awesomeness of Python
the awesomeness continues!
Ease of learning - you’ll see it soon
Very teachable - low syntax overhead
Rapid development cycle - easy to express yourself
Readable, beautiful and brevity - you’ll love to code
Interactive prompt
Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
hour 0: intro awesomeness of Python
the awesomeness continues!
Ease of learning - you’ll see it soon
Very teachable - low syntax overhead
Rapid development cycle - easy to express yourself
Readable, beautiful and brevity - you’ll love to code
Interactive prompt
Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
hour 0: intro awesomeness of Python
the awesomeness continues!
Ease of learning - you’ll see it soon
Very teachable - low syntax overhead
Rapid development cycle - easy to express yourself
Readable, beautiful and brevity - you’ll love to code
Interactive prompt
Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
hour 0: intro awesomeness of Python
©xkcd.com
Satyaki Sikdar© Programming in Python April 22 2016 13 / 137
hour 0: intro awesomeness of Python
places were Py is used
From supercomputers to Instagram, from labs to financial
firms
You can do machine learning, NLP to building web pages and
wrangling social networks
Really hip among startups
Schools like M.I.T., Rice, Stanford, Havard have switched to
Python for their programming courses in the CS curriculum
Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
hour 0: intro awesomeness of Python
places were Py is used
From supercomputers to Instagram, from labs to financial
firms
You can do machine learning, NLP to building web pages and
wrangling social networks
Really hip among startups
Schools like M.I.T., Rice, Stanford, Havard have switched to
Python for their programming courses in the CS curriculum
Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
hour 0: intro awesomeness of Python
places were Py is used
From supercomputers to Instagram, from labs to financial
firms
You can do machine learning, NLP to building web pages and
wrangling social networks
Really hip among startups
Schools like M.I.T., Rice, Stanford, Havard have switched to
Python for their programming courses in the CS curriculum
Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
hour 0: intro awesomeness of Python
places were Py is used
From supercomputers to Instagram, from labs to financial
firms
You can do machine learning, NLP to building web pages and
wrangling social networks
Really hip among startups
Schools like M.I.T., Rice, Stanford, Havard have switched to
Python for their programming courses in the CS curriculum
Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
hour 0: intro indentation
indentation continues
Pseudocode on the left and Python code on the right
Figure: From CLRS
def INSERTION_SORT(A):
for j in xrange(1, len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i -= 1
A[i + 1] = key
Satyaki Sikdar© Programming in Python April 22 2016 15 / 137
hour 0: intro indentation
indentation & Python
It’s absolutely essential to indent Python code.
It seems natural
Braces? Yuck!!
According to PEP8, you must indent every block of code by 4 spaces
Mess up the indentation, and your precious code becomes garbage
from __future__ import braces
# File "<stdin>", line 1
# SyntaxError: not a chance
Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
hour 0: intro indentation
indentation & Python
It’s absolutely essential to indent Python code.
It seems natural
Braces? Yuck!!
According to PEP8, you must indent every block of code by 4 spaces
Mess up the indentation, and your precious code becomes garbage
from __future__ import braces
# File "<stdin>", line 1
# SyntaxError: not a chance
Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
hour 0: intro indentation
indentation & Python
It’s absolutely essential to indent Python code.
It seems natural
Braces? Yuck!!
According to PEP8, you must indent every block of code by 4 spaces
Mess up the indentation, and your precious code becomes garbage
from __future__ import braces
# File "<stdin>", line 1
# SyntaxError: not a chance
Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
hour 0: intro indentation
indentation & Python
It’s absolutely essential to indent Python code.
It seems natural
Braces? Yuck!!
According to PEP8, you must indent every block of code by 4 spaces
Mess up the indentation, and your precious code becomes garbage
from __future__ import braces
# File "<stdin>", line 1
# SyntaxError: not a chance
Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
hour 1: Python 101 the interpreter and more ..
say hello to the interpreter!
Python is an interpreted language. It executes codes line by line
It has an interactive prompt with which you can play around without any fear
The prompt looks like this >>>
You can do everything you want in this interpreter. We’ll play around with it now.
Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
hour 1: Python 101 the interpreter and more ..
say hello to the interpreter!
Python is an interpreted language. It executes codes line by line
It has an interactive prompt with which you can play around without any fear
The prompt looks like this >>>
You can do everything you want in this interpreter. We’ll play around with it now.
Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
hour 1: Python 101 the interpreter and more ..
say hello to the interpreter!
Python is an interpreted language. It executes codes line by line
It has an interactive prompt with which you can play around without any fear
The prompt looks like this >>>
You can do everything you want in this interpreter. We’ll play around with it now.
Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
hour 1: Python 101 the interpreter and more ..
say hello to the interpreter!
Python is an interpreted language. It executes codes line by line
It has an interactive prompt with which you can play around without any fear
The prompt looks like this >>>
You can do everything you want in this interpreter. We’ll play around with it now.
Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
hour 1: Python 101 the interpreter and more ..
the print statement
It’s one of the most used statements in Python
Does what the name says, it prints stuff
It’s very smart - one statement to rule them all - works for every data type - no messy
loops needed
print 1 + 1 # >>> 2
print 'joe root' # >>> joe root (notice the lack of quotes)
print True # >>> True
print 'hello', 'world' # >>> hello world (notice the space)
print 'hello'
print 'world' #hello and world in separate lines
print 'hello',
print 'world' #hello and world in the same line (notice the comma)
Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
hour 1: Python 101 the interpreter and more ..
the print statement
It’s one of the most used statements in Python
Does what the name says, it prints stuff
It’s very smart - one statement to rule them all - works for every data type - no messy
loops needed
print 1 + 1 # >>> 2
print 'joe root' # >>> joe root (notice the lack of quotes)
print True # >>> True
print 'hello', 'world' # >>> hello world (notice the space)
print 'hello'
print 'world' #hello and world in separate lines
print 'hello',
print 'world' #hello and world in the same line (notice the comma)
Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
hour 1: Python 101 the interpreter and more ..
the print statement
It’s one of the most used statements in Python
Does what the name says, it prints stuff
It’s very smart - one statement to rule them all - works for every data type - no messy
loops needed
print 1 + 1 # >>> 2
print 'joe root' # >>> joe root (notice the lack of quotes)
print True # >>> True
print 'hello', 'world' # >>> hello world (notice the space)
print 'hello'
print 'world' #hello and world in separate lines
print 'hello',
print 'world' #hello and world in the same line (notice the comma)
Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
hour 1: Python 101 the interpreter and more ..
the print statement
formatter = '%s %s %s %s'
print formatter % (1, 2, 3, 4)
print formatter % ('one', 'two', 'three', 'four')
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % ('I had this thing.',
'That you could type up right.',
"But it didn't sing.",
'So I said goodnight.')
Satyaki Sikdar© Programming in Python April 22 2016 19 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 data types
data types in Python
There are 6 basic data types in Python
1 integers (int), eg: 1, 23, 1245322
2 long integers (long). These usually end with a L at the end, eg:
1071645932315929337037L
3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is
a valid floating point number.
4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex
number in Python.
5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid
strings, but ’jimmy anderson" or "jimmy anderson’ is not.
6 booleans (bool): True and False
Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 integers
integers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50 + 7 gives 57
* for multiplication. Eg: 50 * 7 gives 350
/ for integer division. Eg: 50 / 7 gives 7 (why?)
% for modulo operation. Eg: 50 % 7 gives 1
** for exponentiation. Eg: 2 ** 7 gives 128
>>, <<, ˜ are also allowed
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
hour 1: Python 101 floats
floating point numbers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50.2 + 7.4 gives 57.6
* for multiplication. Eg: 50.2 * 5 gives 251.0
/ for division. Eg: 50.0 / 7 gives 7.1428
% for modulo operation. Eg: 50.0 % 7.2 gives 6.79999
** for exponentiation. Eg: 2.2 ** 7 gives 249.43578
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
hour 1: Python 101 floats
floating point numbers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50.2 + 7.4 gives 57.6
* for multiplication. Eg: 50.2 * 5 gives 251.0
/ for division. Eg: 50.0 / 7 gives 7.1428
% for modulo operation. Eg: 50.0 % 7.2 gives 6.79999
** for exponentiation. Eg: 2.2 ** 7 gives 249.43578
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
hour 1: Python 101 floats
floating point numbers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50.2 + 7.4 gives 57.6
* for multiplication. Eg: 50.2 * 5 gives 251.0
/ for division. Eg: 50.0 / 7 gives 7.1428
% for modulo operation. Eg: 50.0 % 7.2 gives 6.79999
** for exponentiation. Eg: 2.2 ** 7 gives 249.43578
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
hour 1: Python 101 floats
floating point numbers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50.2 + 7.4 gives 57.6
* for multiplication. Eg: 50.2 * 5 gives 251.0
/ for division. Eg: 50.0 / 7 gives 7.1428
% for modulo operation. Eg: 50.0 % 7.2 gives 6.79999
** for exponentiation. Eg: 2.2 ** 7 gives 249.43578
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
hour 1: Python 101 floats
floating point numbers
Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise
to you.
+ for addition. Eg: 50.2 + 7.4 gives 57.6
* for multiplication. Eg: 50.2 * 5 gives 251.0
/ for division. Eg: 50.0 / 7 gives 7.1428
% for modulo operation. Eg: 50.0 % 7.2 gives 6.79999
** for exponentiation. Eg: 2.2 ** 7 gives 249.43578
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
hour 1: Python 101 complex numbers
complex numbers
Note: j is used in place of i
+ for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)
* for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)
/ for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)
% for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)
** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
hour 1: Python 101 complex numbers
complex numbers
Note: j is used in place of i
+ for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)
* for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)
/ for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)
% for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)
** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
hour 1: Python 101 complex numbers
complex numbers
Note: j is used in place of i
+ for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)
* for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)
/ for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)
% for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)
** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
hour 1: Python 101 complex numbers
complex numbers
Note: j is used in place of i
+ for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)
* for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)
/ for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)
% for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)
** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
hour 1: Python 101 complex numbers
complex numbers
Note: j is used in place of i
+ for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)
* for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)
/ for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)
% for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)
** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j
Parenthization of expressions is allowed with the help of ()
Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
hour 1: Python 101 strings
no strings attached!
Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH
Bigger strings consist of smaller strings. There’s no such thing as a character in Python.
+ used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’
and ’Cook’ + ’Alastair’ gives ’CookAlastair’
* used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’
Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
hour 1: Python 101 strings
no strings attached!
Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH
Bigger strings consist of smaller strings. There’s no such thing as a character in Python.
+ used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’
and ’Cook’ + ’Alastair’ gives ’CookAlastair’
* used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’
Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
hour 1: Python 101 strings
no strings attached!
Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH
Bigger strings consist of smaller strings. There’s no such thing as a character in Python.
+ used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’
and ’Cook’ + ’Alastair’ gives ’CookAlastair’
* used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’
Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
hour 1: Python 101 strings
no strings attached!
Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH
Bigger strings consist of smaller strings. There’s no such thing as a character in Python.
+ used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’
and ’Cook’ + ’Alastair’ gives ’CookAlastair’
* used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’
Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
hour 1: Python 101 strings
string methods - I
Here’s a subset of the many in-built functions and methods that can be used with strings.
len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6
indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1]
=> ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so
on.
slicing: Returns a part of the string. So string[start: end] slices the string from index =
start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2:
6] => ’hate’
Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
hour 1: Python 101 strings
string methods - I
Here’s a subset of the many in-built functions and methods that can be used with strings.
len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6
indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1]
=> ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so
on.
slicing: Returns a part of the string. So string[start: end] slices the string from index =
start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2:
6] => ’hate’
Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
hour 1: Python 101 strings
string methods - I
Here’s a subset of the many in-built functions and methods that can be used with strings.
len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6
indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1]
=> ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so
on.
slicing: Returns a part of the string. So string[start: end] slices the string from index =
start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2:
6] => ’hate’
Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
hour 1: Python 101 strings
string methods - II
s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home
for imaginary friends’ .count (’fo’) = 2
s.find(substring) :- gives you the index of the substring in the string. Eg:
’Alastair’.find(’stair’) = 3
s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair
Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ]
If delim is omitted, whitespace is used by default
Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
hour 1: Python 101 strings
string methods - II
s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home
for imaginary friends’ .count (’fo’) = 2
s.find(substring) :- gives you the index of the substring in the string. Eg:
’Alastair’.find(’stair’) = 3
s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair
Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ]
If delim is omitted, whitespace is used by default
Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
hour 1: Python 101 strings
string methods - II
s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home
for imaginary friends’ .count (’fo’) = 2
s.find(substring) :- gives you the index of the substring in the string. Eg:
’Alastair’.find(’stair’) = 3
s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair
Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ]
If delim is omitted, whitespace is used by default
Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
hour 1: Python 101 strings
string slicing - revisited
So far, we have sliced strings in a manner like st[start: end]
You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaults
to 1. But what does that mean? Let’s find out!
st = '0123456789'
for c in st[: : 1]:
print c, #output: 0 1 2 3 4 5 6 7 8 9
for c in st[: : 2]:
print c, #output: 0 2 4 6 8
for c in st[: : 3]:
print c, #output: 0 3 6 9
for c in st[: : -1]:
print c, #output: 9 8 7 6 5 4 3 2 1 0 WHOA! Really?!
# what about st[: : -2]? Find it out!
Satyaki Sikdar© Programming in Python April 22 2016 27 / 137
hour 1: Python 101 strings
string slicing - revisited
So far, we have sliced strings in a manner like st[start: end]
You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaults
to 1. But what does that mean? Let’s find out!
st = '0123456789'
for c in st[: : 1]:
print c, #output: 0 1 2 3 4 5 6 7 8 9
for c in st[: : 2]:
print c, #output: 0 2 4 6 8
for c in st[: : 3]:
print c, #output: 0 3 6 9
for c in st[: : -1]:
print c, #output: 9 8 7 6 5 4 3 2 1 0 WHOA! Really?!
# what about st[: : -2]? Find it out!
Satyaki Sikdar© Programming in Python April 22 2016 27 / 137
hour 1: Python 101 strings
palindrome checking
A palindrome is a word, phrase, number, or other sequence of characters which reads the
same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,
Panama!’
Often it’s allowed to skip over spaces and punctuation marks
It’s a classic problem while dealing with strings. And we’ll stick to character-unit
palindromes. Example: redivider, noon, radar, madam, refer, etc.
We’ll see a simple one liner code that checks if a string is a palindrome.
>>> st = 'refer'
>>> if st == st[: : -1]: # st == st.reverse() does the same thing
print st, 'is a palindrome'
else:
print st, 'is not a palindrome'
Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
hour 1: Python 101 strings
palindrome checking
A palindrome is a word, phrase, number, or other sequence of characters which reads the
same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,
Panama!’
Often it’s allowed to skip over spaces and punctuation marks
It’s a classic problem while dealing with strings. And we’ll stick to character-unit
palindromes. Example: redivider, noon, radar, madam, refer, etc.
We’ll see a simple one liner code that checks if a string is a palindrome.
>>> st = 'refer'
>>> if st == st[: : -1]: # st == st.reverse() does the same thing
print st, 'is a palindrome'
else:
print st, 'is not a palindrome'
Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
hour 1: Python 101 strings
palindrome checking
A palindrome is a word, phrase, number, or other sequence of characters which reads the
same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,
Panama!’
Often it’s allowed to skip over spaces and punctuation marks
It’s a classic problem while dealing with strings. And we’ll stick to character-unit
palindromes. Example: redivider, noon, radar, madam, refer, etc.
We’ll see a simple one liner code that checks if a string is a palindrome.
>>> st = 'refer'
>>> if st == st[: : -1]: # st == st.reverse() does the same thing
print st, 'is a palindrome'
else:
print st, 'is not a palindrome'
Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
hour 1: Python 101 strings
multi-line strings and escape characters
Multi-line strings
Multi-line strings are different from ordinary strings. As the name suggests, they can span
over multiple lines
Enclosed by a pair of ”’ or """
They support all the string operations - indexing, slicing and dicing...
End of lines are marked with the EOL (n) character
Escape characters
 acts as the escape character
"I am 5'11" tall." # escape double-quote inside the string
'I am 5'11" tall.' # escape single-quote inside the string
Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
hour 1: Python 101 strings
multi-line strings and escape characters
Multi-line strings
Multi-line strings are different from ordinary strings. As the name suggests, they can span
over multiple lines
Enclosed by a pair of ”’ or """
They support all the string operations - indexing, slicing and dicing...
End of lines are marked with the EOL (n) character
Escape characters
 acts as the escape character
"I am 5'11" tall." # escape double-quote inside the string
'I am 5'11" tall.' # escape single-quote inside the string
Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
hour 1: Python 101 strings
multi-line strings and escape characters
Multi-line strings
Multi-line strings are different from ordinary strings. As the name suggests, they can span
over multiple lines
Enclosed by a pair of ”’ or """
They support all the string operations - indexing, slicing and dicing...
End of lines are marked with the EOL (n) character
Escape characters
 acts as the escape character
"I am 5'11" tall." # escape double-quote inside the string
'I am 5'11" tall.' # escape single-quote inside the string
Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
hour 1: Python 101 strings
multi-line strings and escape characters
Multi-line strings
Multi-line strings are different from ordinary strings. As the name suggests, they can span
over multiple lines
Enclosed by a pair of ”’ or """
They support all the string operations - indexing, slicing and dicing...
End of lines are marked with the EOL (n) character
Escape characters
 acts as the escape character
"I am 5'11" tall." # escape double-quote inside the string
'I am 5'11" tall.' # escape single-quote inside the string
Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
hour 1: Python 101 strings
multi-line strings and escape characters
Multi-line strings
Multi-line strings are different from ordinary strings. As the name suggests, they can span
over multiple lines
Enclosed by a pair of ”’ or """
They support all the string operations - indexing, slicing and dicing...
End of lines are marked with the EOL (n) character
Escape characters
 acts as the escape character
"I am 5'11" tall." # escape double-quote inside the string
'I am 5'11" tall.' # escape single-quote inside the string
Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
hour 1: Python 101 strings
the Boolean data type
They represent the logical True and False. The operations that they support are as follows:
Negation: Using the word not before True or False negates it. >>> not True yields False
and >>> not False yields True
Logical and: The result is True if and only if every argument is True. In Python, use the
word and
Logical or: The result is False if and only if every argument is False. In Python, use the
word or
Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
hour 1: Python 101 strings
the Boolean data type
They represent the logical True and False. The operations that they support are as follows:
Negation: Using the word not before True or False negates it. >>> not True yields False
and >>> not False yields True
Logical and: The result is True if and only if every argument is True. In Python, use the
word and
Logical or: The result is False if and only if every argument is False. In Python, use the
word or
Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
hour 1: Python 101 strings
the Boolean data type
They represent the logical True and False. The operations that they support are as follows:
Negation: Using the word not before True or False negates it. >>> not True yields False
and >>> not False yields True
Logical and: The result is True if and only if every argument is True. In Python, use the
word and
Logical or: The result is False if and only if every argument is False. In Python, use the
word or
Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
hour 1: Python 101 strings
truth tables for logical and and logical or
A B A or B A and B
False False False False
False True True False
True False True False
True True True True
Satyaki Sikdar© Programming in Python April 22 2016 31 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 strings
logical comparisons
The comparisons yield either True or False
Equals (==): 2 == 3 is False
Not equal (!=): 2 != 3 is True
Greater than (>): 2 > 3 is False
Lesser than (<): 2 < 3 is True
Greater than or equal to (>=): 2 >= 4 is False
Lesser than or equal to (<=): 2 <= 4 is True
Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
variables!
Variables provide a way to associate names with objects
I personally prefer under_bars over camelCase. It’s up to you to decide
A variable is just a name. An object can have one, more than one or no names associated
with it.
Assignment statements are used to assign values to variables. a = 15
Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’
and it’ll be alright!
Note: julia, Julia, and JULIA are all different
Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
hour 1: Python 101 variables and bindings
bindings
Consider the code
pi = 3.14159
radius = 11.2
area = pi * (radius ** 2)
radius = 14.3
Figure: Binding of variables to objects
Satyaki Sikdar© Programming in Python April 22 2016 34 / 137
hour 1: Python 101 variables and bindings
meaningful names!
a = 3.14159
b = 11.2
c = a * (b ** 2)
pi = 3.14159
diameter = 11.2
area = pi * (diameter ** 2)
The two codes to Python are exactly the same
To a human, they are pretty different! The code on the right is better, but there’s a
problem?!
The variable should have been called radius instead of diameter, or the area formula is
wrong!
Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
hour 1: Python 101 variables and bindings
meaningful names!
a = 3.14159
b = 11.2
c = a * (b ** 2)
pi = 3.14159
diameter = 11.2
area = pi * (diameter ** 2)
The two codes to Python are exactly the same
To a human, they are pretty different! The code on the right is better, but there’s a
problem?!
The variable should have been called radius instead of diameter, or the area formula is
wrong!
Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
hour 1: Python 101 variables and bindings
meaningful names!
a = 3.14159
b = 11.2
c = a * (b ** 2)
pi = 3.14159
diameter = 11.2
area = pi * (diameter ** 2)
The two codes to Python are exactly the same
To a human, they are pretty different! The code on the right is better, but there’s a
problem?!
The variable should have been called radius instead of diameter, or the area formula is
wrong!
Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
hour 1: Python 101 variables and bindings
a comic from xkcd.com
Satyaki Sikdar© Programming in Python April 22 2016 36 / 137
hour 1: Python 101 variables and bindings
the names which must not be given!
and as assert
break class continue
def del elif
else except exec
finally for from
global if import
in is lambda
not or pass
print raise return
try while with
yield
Satyaki Sikdar© Programming in Python April 22 2016 37 / 137
hour 1: Python 101 basic i/o
taking input from the user!
name = raw_input('Enter something!')
print name
#example output: Edwin
print type(name)
#example output: <type 'str'>
Satyaki Sikdar© Programming in Python April 22 2016 38 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 1: Python 101 basic i/o
raw_input returns a string
What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer
12
float(’12.4’) gives 12.4 (a float)
int(’12.4’) makes it 12 (an integer)
float(12) makes it 12.0 (a float)
Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError
Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
hour 2: ifs, buts and repeats conditionals
Satyaki Sikdar© Programming in Python April 22 2016 40 / 137
hour 2: ifs, buts and repeats conditionals
making decisions
Making decisions are an integral part of our lives. Thus, it becomes essential for our codes
to make decisions too!
Python has if, else and elif to help your code make decisions
The syntax is as follows
if boolean_expression1:
do_something
elif boolean_expression2:
do_something_different
else:
do_something_else
Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
hour 2: ifs, buts and repeats conditionals
making decisions
Making decisions are an integral part of our lives. Thus, it becomes essential for our codes
to make decisions too!
Python has if, else and elif to help your code make decisions
The syntax is as follows
if boolean_expression1:
do_something
elif boolean_expression2:
do_something_different
else:
do_something_else
Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
hour 2: ifs, buts and repeats conditionals
making decisions
Making decisions are an integral part of our lives. Thus, it becomes essential for our codes
to make decisions too!
Python has if, else and elif to help your code make decisions
The syntax is as follows
if boolean_expression1:
do_something
elif boolean_expression2:
do_something_different
else:
do_something_else
Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
hour 2: ifs, buts and repeats conditionals
a simple illustration I
Comparing the values of two variables
x = int(raw_input('Enter 1st number'))
y = int(raw_input('Enter 2nd number'))
if x == y:
print 'the numbers are equal'
elif x > y:
print 'the first number is bigger'
else:
print 'the second number is bigger'
Satyaki Sikdar© Programming in Python April 22 2016 42 / 137
hour 2: ifs, buts and repeats conditionals
a simple illustration II
Nested conditionals
Divisibility by 6
x = int(raw_input("Enter a number: "))
if x % 2 == 0:
if x % 3 == 0:
print 'Divisible by both 2 and 3'
else:
print 'Divisible by 2, but not by 3'
elif x % 3 == 0:
print 'Divisible by 3 and not by 2'
else:
print 'Divisible by neither 2 nor 3'
Satyaki Sikdar© Programming in Python April 22 2016 43 / 137
hour 2: ifs, buts and repeats conditionals
the in keyword
The in keyword is used for containment checking
Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian
botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False
Thus in can be used in if, elif statements.
Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
hour 2: ifs, buts and repeats conditionals
the in keyword
The in keyword is used for containment checking
Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian
botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False
Thus in can be used in if, elif statements.
Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
hour 2: ifs, buts and repeats conditionals
the in keyword
The in keyword is used for containment checking
Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian
botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False
Thus in can be used in if, elif statements.
Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
hour 2: ifs, buts and repeats looping constructs
loops: the basic idea
Satyaki Sikdar© Programming in Python April 22 2016 45 / 137
hour 2: ifs, buts and repeats looping constructs
say hello to while loops
while loops in Python are no different than the while loops in other common languages.
Phew!
It’s similar to a conditional statement. But, no else blocks
As long as the condition is valid, the loop body keeps executing. The condition is
re-evaluated each time
Let’s look at an example.
# squaring an integer, the hard way
>>> x = 4
>>> ans = 0
>>> iters_left = x
>>> while iters_left != 0:
ans = ans + x
iters_left = iters_left - 1
>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
hour 2: ifs, buts and repeats looping constructs
say hello to while loops
while loops in Python are no different than the while loops in other common languages.
Phew!
It’s similar to a conditional statement. But, no else blocks
As long as the condition is valid, the loop body keeps executing. The condition is
re-evaluated each time
Let’s look at an example.
# squaring an integer, the hard way
>>> x = 4
>>> ans = 0
>>> iters_left = x
>>> while iters_left != 0:
ans = ans + x
iters_left = iters_left - 1
>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
hour 2: ifs, buts and repeats looping constructs
say hello to while loops
while loops in Python are no different than the while loops in other common languages.
Phew!
It’s similar to a conditional statement. But, no else blocks
As long as the condition is valid, the loop body keeps executing. The condition is
re-evaluated each time
Let’s look at an example.
# squaring an integer, the hard way
>>> x = 4
>>> ans = 0
>>> iters_left = x
>>> while iters_left != 0:
ans = ans + x
iters_left = iters_left - 1
>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
hour 2: ifs, buts and repeats looping constructs
squaring the hard way
taking x = 4 as an example
test # x ans iters_left iters_left != 0
1 4 0 4 True
2 4 4 3 True
3 4 8 2 True
4 4 12 1 True
5 4 16 0 False
Boom! When iters_left is 0, we have our answer in ans
For what values of x will the program terminate?
Satyaki Sikdar© Programming in Python April 22 2016 47 / 137
hour 2: ifs, buts and repeats looping constructs
the correctness of the program
It’s very important to check if the procedure works for all x
We’ve already proved that it works when x is a positive integer
What about when x is 0? It works! The body of the while loop is not executed. So, ans
stays at 0!
What about when x is negative? Let’s see! Say x = -3.
test # x ans iters_left iters_left != 0
1 -3 0 -3 True
2 -3 -3 -4 True
3 -3 -6 -5 True
4 -3 -9 -6 True
5 -3 -12 -7 True
6 -3 -15 -8 True
OOPS! It hasn’t stop when it’s supposed to! :(
Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
hour 2: ifs, buts and repeats looping constructs
the correctness of the program
It’s very important to check if the procedure works for all x
We’ve already proved that it works when x is a positive integer
What about when x is 0? It works! The body of the while loop is not executed. So, ans
stays at 0!
What about when x is negative? Let’s see! Say x = -3.
test # x ans iters_left iters_left != 0
1 -3 0 -3 True
2 -3 -3 -4 True
3 -3 -6 -5 True
4 -3 -9 -6 True
5 -3 -12 -7 True
6 -3 -15 -8 True
OOPS! It hasn’t stop when it’s supposed to! :(
Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
hour 2: ifs, buts and repeats looping constructs
the correctness of the program
It’s very important to check if the procedure works for all x
We’ve already proved that it works when x is a positive integer
What about when x is 0? It works! The body of the while loop is not executed. So, ans
stays at 0!
What about when x is negative? Let’s see! Say x = -3.
test # x ans iters_left iters_left != 0
1 -3 0 -3 True
2 -3 -3 -4 True
3 -3 -6 -5 True
4 -3 -9 -6 True
5 -3 -12 -7 True
6 -3 -15 -8 True
OOPS! It hasn’t stop when it’s supposed to! :(
Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
hour 2: ifs, buts and repeats looping constructs
does the code ever end??!!
Things start to get a little fishy when x is negative
Does the program ever end? NO!!
Is it a problem? YES !!
Is there any way to fix this? Hell yeah! Let’s see the code.
>>> x = -4
>>> ans = 0
>>> iters_left = abs(x) #the absolute value of x
>>> while iters_left != 0:
ans = ans + abs(x)
iters_left = iters_left - 1
>>> print x, 'squared is', ans
Does it make things better? Yes indeed! We got a working program that squares all
integers! Yay!
Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
hour 2: ifs, buts and repeats looping constructs
does the code ever end??!!
Things start to get a little fishy when x is negative
Does the program ever end? NO!!
Is it a problem? YES !!
Is there any way to fix this? Hell yeah! Let’s see the code.
>>> x = -4
>>> ans = 0
>>> iters_left = abs(x) #the absolute value of x
>>> while iters_left != 0:
ans = ans + abs(x)
iters_left = iters_left - 1
>>> print x, 'squared is', ans
Does it make things better? Yes indeed! We got a working program that squares all
integers! Yay!
Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
hour 2: ifs, buts and repeats looping constructs
does the code ever end??!!
Things start to get a little fishy when x is negative
Does the program ever end? NO!!
Is it a problem? YES !!
Is there any way to fix this? Hell yeah! Let’s see the code.
>>> x = -4
>>> ans = 0
>>> iters_left = abs(x) #the absolute value of x
>>> while iters_left != 0:
ans = ans + abs(x)
iters_left = iters_left - 1
>>> print x, 'squared is', ans
Does it make things better? Yes indeed! We got a working program that squares all
integers! Yay!
Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
hour 2: ifs, buts and repeats looping constructs
does the code ever end??!!
Things start to get a little fishy when x is negative
Does the program ever end? NO!!
Is it a problem? YES !!
Is there any way to fix this? Hell yeah! Let’s see the code.
>>> x = -4
>>> ans = 0
>>> iters_left = abs(x) #the absolute value of x
>>> while iters_left != 0:
ans = ans + abs(x)
iters_left = iters_left - 1
>>> print x, 'squared is', ans
Does it make things better? Yes indeed! We got a working program that squares all
integers! Yay!
Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
hour 2: ifs, buts and repeats looping constructs
does the code ever end??!!
Things start to get a little fishy when x is negative
Does the program ever end? NO!!
Is it a problem? YES !!
Is there any way to fix this? Hell yeah! Let’s see the code.
>>> x = -4
>>> ans = 0
>>> iters_left = abs(x) #the absolute value of x
>>> while iters_left != 0:
ans = ans + abs(x)
iters_left = iters_left - 1
>>> print x, 'squared is', ans
Does it make things better? Yes indeed! We got a working program that squares all
integers! Yay!
Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
hour 2: ifs, buts and repeats looping constructs
for loops
In Python, for loops are a little different. They are effectively for each loops
Syntax:
for item in iterable:
code block #notice the indentation
Strings are iterable. So are lists, tuples, dictionaries, sets, ...
Example:
>>> st = 'cuts like a knife!'
>>> for x in st:
print x,
>>> cuts like a knife!
Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
hour 2: ifs, buts and repeats looping constructs
for loops
In Python, for loops are a little different. They are effectively for each loops
Syntax:
for item in iterable:
code block #notice the indentation
Strings are iterable. So are lists, tuples, dictionaries, sets, ...
Example:
>>> st = 'cuts like a knife!'
>>> for x in st:
print x,
>>> cuts like a knife!
Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
hour 2: ifs, buts and repeats looping constructs
for loops
In Python, for loops are a little different. They are effectively for each loops
Syntax:
for item in iterable:
code block #notice the indentation
Strings are iterable. So are lists, tuples, dictionaries, sets, ...
Example:
>>> st = 'cuts like a knife!'
>>> for x in st:
print x,
>>> cuts like a knife!
Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
hour 2: ifs, buts and repeats looping constructs
how does it work?
for item in iterable:
code block
for each item (x) in the iterable, execute the code block repeatedly as long as the iterable is not
exhausted. You may or may not use the item (x).
# figuring out the length of a string w/o using len()
>>> length = 0
>>> st = 'rocky mountain high'
>>> for c in st:
length += 1
>>> print 'the length of the string is', length
Output: the length of the string is 19
Satyaki Sikdar© Programming in Python April 22 2016 51 / 137
hour 2: ifs, buts and repeats looping constructs
a few more illustrations
This time we’ll use the item in the for loop
>>> st = 'rocky mountain high'
>>> for c in st:
if c == 'o':
print c.upper(),
else:
print c,
>>> rOcky mOuntain high
>>> st = 'Ryan ten Doeschate'
>>> for c in st[: : -1]:
print c,
>>> etahcseoD net nayR
Satyaki Sikdar© Programming in Python April 22 2016 52 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
the xrange function
An arithmetic series (AP) has parameters start, stop and step
xrange() is used to generate an iterator for an AP in Python
xrange(start, stop, step) will generate numbers of the form:
start, start + step, start + 2 ∗ step, ..., in the set [start, end)
If one argument (x) is passed, start = 0, stop = x, step = 1
>>> for no in xrange(5):
print no, #output: 0 1 2 3 4
If two arguments (x, y) are passed, start = x, stop = y, step = 1
>>> for no in xrange(2, 5):
print no, #output: 2 3 4
If three (x, y, z) are passed, start = x, stop = y, step = z
>>> for no in xrange(1, 6, 2):
print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
hour 2: ifs, buts and repeats looping constructs
loop condition evaluation
>>> x = 4
>>> for j in range(x):
for i in range(x):
print i
x = 2
0
1
2
3
0
1
0
1
0
1
Seems bizarre? Let’s break it down
The first range function is evaluated once with x = 4, so
come what may, the outer loop will run 4 times
Each time, the inner loop would run x times, so the first
time it runs 4 times
But inside, x becomes 2, and then from second time on,
the inner loop runs twice
Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
hour 2: ifs, buts and repeats looping constructs
loop condition evaluation
>>> x = 4
>>> for j in range(x):
for i in range(x):
print i
x = 2
0
1
2
3
0
1
0
1
0
1
Seems bizarre? Let’s break it down
The first range function is evaluated once with x = 4, so
come what may, the outer loop will run 4 times
Each time, the inner loop would run x times, so the first
time it runs 4 times
But inside, x becomes 2, and then from second time on,
the inner loop runs twice
Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
hour 2: ifs, buts and repeats looping constructs
loop condition evaluation
>>> x = 4
>>> for j in range(x):
for i in range(x):
print i
x = 2
0
1
2
3
0
1
0
1
0
1
Seems bizarre? Let’s break it down
The first range function is evaluated once with x = 4, so
come what may, the outer loop will run 4 times
Each time, the inner loop would run x times, so the first
time it runs 4 times
But inside, x becomes 2, and then from second time on,
the inner loop runs twice
Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
hour 2: ifs, buts and repeats looping constructs
loop condition evaluation
>>> x = 4
>>> for j in range(x):
for i in range(x):
print i
x = 2
0
1
2
3
0
1
0
1
0
1
Seems bizarre? Let’s break it down
The first range function is evaluated once with x = 4, so
come what may, the outer loop will run 4 times
Each time, the inner loop would run x times, so the first
time it runs 4 times
But inside, x becomes 2, and then from second time on,
the inner loop runs twice
Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
hour 2: ifs, buts and repeats bisection search
bisection search - the hunt for
√
x
>>> x = int(raw_input("Enter a number"))
>>> eps = 0.01; num_guess = 0
>>> low = 0.0
>>> high = x
>>> ans = (low + high) / 2.0
>>> while abs(ans ** 2 - x) >= eps:
print 'guess:', num_guess, 'low:', low, 'high:', high, 'ans:', ans
num_guess += 1
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (low + high) / 2.0
>>> print ans, 'is close to sqrt of', x
Satyaki Sikdar© Programming in Python April 22 2016 55 / 137
hour 2: ifs, buts and repeats floating points
floating point woes
>>> x = 0.0
>>> for i in xrange(10):
x = x + 0.1
>>> if x == 1.0:
print x, '= 1.0'
>>> else:
print x, 'is not 1.0'
The output? 1.0 is not 1.0
What on earth is going on? Has Python gone nuts?
Let’s dig deeper.
In the memory, every number is stored in binary. Let’s
try to figure out what’s the binary representation for (a)
(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2
(0.1)10 = (?)2? What about 3
32 = 0.9375? How about
25
256? Turns out, no matter how many bits you use, you
can’t have a perfect 0.1 in memory! So round up!!
So, now we know that x at the end is not a perfect 1, so the equality test fails
But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t
alway the actual value
Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
hour 2: ifs, buts and repeats floating points
floating point woes
>>> x = 0.0
>>> for i in xrange(10):
x = x + 0.1
>>> if x == 1.0:
print x, '= 1.0'
>>> else:
print x, 'is not 1.0'
The output? 1.0 is not 1.0
What on earth is going on? Has Python gone nuts?
Let’s dig deeper.
In the memory, every number is stored in binary. Let’s
try to figure out what’s the binary representation for (a)
(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2
(0.1)10 = (?)2? What about 3
32 = 0.9375? How about
25
256? Turns out, no matter how many bits you use, you
can’t have a perfect 0.1 in memory! So round up!!
So, now we know that x at the end is not a perfect 1, so the equality test fails
But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t
alway the actual value
Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
hour 2: ifs, buts and repeats floating points
floating point woes
>>> x = 0.0
>>> for i in xrange(10):
x = x + 0.1
>>> if x == 1.0:
print x, '= 1.0'
>>> else:
print x, 'is not 1.0'
The output? 1.0 is not 1.0
What on earth is going on? Has Python gone nuts?
Let’s dig deeper.
In the memory, every number is stored in binary. Let’s
try to figure out what’s the binary representation for (a)
(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2
(0.1)10 = (?)2? What about 3
32 = 0.9375? How about
25
256? Turns out, no matter how many bits you use, you
can’t have a perfect 0.1 in memory! So round up!!
So, now we know that x at the end is not a perfect 1, so the equality test fails
But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t
alway the actual value
Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
hour 2: ifs, buts and repeats floating points
floating point woes
>>> x = 0.0
>>> for i in xrange(10):
x = x + 0.1
>>> if x == 1.0:
print x, '= 1.0'
>>> else:
print x, 'is not 1.0'
The output? 1.0 is not 1.0
What on earth is going on? Has Python gone nuts?
Let’s dig deeper.
In the memory, every number is stored in binary. Let’s
try to figure out what’s the binary representation for (a)
(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2
(0.1)10 = (?)2? What about 3
32 = 0.9375? How about
25
256? Turns out, no matter how many bits you use, you
can’t have a perfect 0.1 in memory! So round up!!
So, now we know that x at the end is not a perfect 1, so the equality test fails
But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t
alway the actual value
Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
hour 2: ifs, buts and repeats floating points
floating point woes
>>> x = 0.0
>>> for i in xrange(10):
x = x + 0.1
>>> if x == 1.0:
print x, '= 1.0'
>>> else:
print x, 'is not 1.0'
The output? 1.0 is not 1.0
What on earth is going on? Has Python gone nuts?
Let’s dig deeper.
In the memory, every number is stored in binary. Let’s
try to figure out what’s the binary representation for (a)
(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2
(0.1)10 = (?)2? What about 3
32 = 0.9375? How about
25
256? Turns out, no matter how many bits you use, you
can’t have a perfect 0.1 in memory! So round up!!
So, now we know that x at the end is not a perfect 1, so the equality test fails
But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t
alway the actual value
Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 lists
lists
The list is a container that holds a number of other objects, in a given order.
Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable
Lists are enclosed in square brackets [ ] and the elements are separated by commas.
Example: [1, 2, 3, 5] is a valid list
It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list
Lists support indexing and slicing in the exact same manner as strings do.
They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1,
2, 1, 2]
Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
hour 3: data structures 101 list operations
basic functions and operations
Empty list is declared as [ ] or list()
len() gives you the length of the list. So, len([1, 5, 6]) gives 3
lst[i] returns the item at index i (the first item has index 0)
Lists, unlike strings, support item assignment
>>> lst = [1, 3, 4] >>> lst[1] = 7
>>> print lst >>> print lst
[1, 3, 4] [1, 7, 4]
Adding a new element to a list is done using append
>>> lst = [1, 3, 4] >>> lst.append(10)
>>> print lst >>> print lst
[1, 3, 4] [1, 3, 4, 10]
Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
hour 3: data structures 101 list operations
basic functions and operations
Empty list is declared as [ ] or list()
len() gives you the length of the list. So, len([1, 5, 6]) gives 3
lst[i] returns the item at index i (the first item has index 0)
Lists, unlike strings, support item assignment
>>> lst = [1, 3, 4] >>> lst[1] = 7
>>> print lst >>> print lst
[1, 3, 4] [1, 7, 4]
Adding a new element to a list is done using append
>>> lst = [1, 3, 4] >>> lst.append(10)
>>> print lst >>> print lst
[1, 3, 4] [1, 3, 4, 10]
Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
hour 3: data structures 101 list operations
basic functions and operations
Empty list is declared as [ ] or list()
len() gives you the length of the list. So, len([1, 5, 6]) gives 3
lst[i] returns the item at index i (the first item has index 0)
Lists, unlike strings, support item assignment
>>> lst = [1, 3, 4] >>> lst[1] = 7
>>> print lst >>> print lst
[1, 3, 4] [1, 7, 4]
Adding a new element to a list is done using append
>>> lst = [1, 3, 4] >>> lst.append(10)
>>> print lst >>> print lst
[1, 3, 4] [1, 3, 4, 10]
Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
hour 3: data structures 101 list operations
basic functions and operations
Empty list is declared as [ ] or list()
len() gives you the length of the list. So, len([1, 5, 6]) gives 3
lst[i] returns the item at index i (the first item has index 0)
Lists, unlike strings, support item assignment
>>> lst = [1, 3, 4] >>> lst[1] = 7
>>> print lst >>> print lst
[1, 3, 4] [1, 7, 4]
Adding a new element to a list is done using append
>>> lst = [1, 3, 4] >>> lst.append(10)
>>> print lst >>> print lst
[1, 3, 4] [1, 3, 4, 10]
Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
hour 3: data structures 101 list operations
basic functions and operations
Empty list is declared as [ ] or list()
len() gives you the length of the list. So, len([1, 5, 6]) gives 3
lst[i] returns the item at index i (the first item has index 0)
Lists, unlike strings, support item assignment
>>> lst = [1, 3, 4] >>> lst[1] = 7
>>> print lst >>> print lst
[1, 3, 4] [1, 7, 4]
Adding a new element to a list is done using append
>>> lst = [1, 3, 4] >>> lst.append(10)
>>> print lst >>> print lst
[1, 3, 4] [1, 3, 4, 10]
Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
hour 3: data structures 101 list operations
Append adds one element at a time. lst.append(1, 2) would raise an error!
So, what if we want to append more than one items? It’s called extending a list
>>> lst = [1, 5, 9] >>> #what if we use + instead?
>>> print lst >>> lst2 = [8, 9, 10]
[1, 5, 9] >>> lst3 = lst2 + [3, 4]
>>> lst.extend([2, 5, 10]) >>> print lst3
>>> print lst [8, 9, 10, 3, 4]
[1, 5, 9, 2, 5, 10]
Satyaki Sikdar© Programming in Python April 22 2016 59 / 137
hour 3: data structures 101 list operations
Append adds one element at a time. lst.append(1, 2) would raise an error!
So, what if we want to append more than one items? It’s called extending a list
>>> lst = [1, 5, 9] >>> #what if we use + instead?
>>> print lst >>> lst2 = [8, 9, 10]
[1, 5, 9] >>> lst3 = lst2 + [3, 4]
>>> lst.extend([2, 5, 10]) >>> print lst3
>>> print lst [8, 9, 10, 3, 4]
[1, 5, 9, 2, 5, 10]
Satyaki Sikdar© Programming in Python April 22 2016 59 / 137
hour 3: data structures 101 list operations
Append adds a new element only to the end
Insert gives more flexibility. It allows you to specify the position as well
Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by
lst.insert(0, x), and at the end by lst.insert(len(lst), x)
What about removing things? lst.pop() removes and returns the last element.
lst.pop(pos) removes the element from a specific position.
>>> lst = [1, 2, 3, 4, 5] >>> print lst.pop()
>>> print lst 5
[1, 2, 3, 4, 5] >>> print lst
>>> lst.insert(2, 10) [1, 2, 10, 3, 4]
>>> print lst >>> print lst.pop(3)
[1, 2, 10, 3, 4, 5] 3
Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
hour 3: data structures 101 list operations
Append adds a new element only to the end
Insert gives more flexibility. It allows you to specify the position as well
Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by
lst.insert(0, x), and at the end by lst.insert(len(lst), x)
What about removing things? lst.pop() removes and returns the last element.
lst.pop(pos) removes the element from a specific position.
>>> lst = [1, 2, 3, 4, 5] >>> print lst.pop()
>>> print lst 5
[1, 2, 3, 4, 5] >>> print lst
>>> lst.insert(2, 10) [1, 2, 10, 3, 4]
>>> print lst >>> print lst.pop(3)
[1, 2, 10, 3, 4, 5] 3
Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
hour 3: data structures 101 list operations
Append adds a new element only to the end
Insert gives more flexibility. It allows you to specify the position as well
Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by
lst.insert(0, x), and at the end by lst.insert(len(lst), x)
What about removing things? lst.pop() removes and returns the last element.
lst.pop(pos) removes the element from a specific position.
>>> lst = [1, 2, 3, 4, 5] >>> print lst.pop()
>>> print lst 5
[1, 2, 3, 4, 5] >>> print lst
>>> lst.insert(2, 10) [1, 2, 10, 3, 4]
>>> print lst >>> print lst.pop(3)
[1, 2, 10, 3, 4, 5] 3
Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
hour 3: data structures 101 list operations
Append adds a new element only to the end
Insert gives more flexibility. It allows you to specify the position as well
Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by
lst.insert(0, x), and at the end by lst.insert(len(lst), x)
What about removing things? lst.pop() removes and returns the last element.
lst.pop(pos) removes the element from a specific position.
>>> lst = [1, 2, 3, 4, 5] >>> print lst.pop()
>>> print lst 5
[1, 2, 3, 4, 5] >>> print lst
>>> lst.insert(2, 10) [1, 2, 10, 3, 4]
>>> print lst >>> print lst.pop(3)
[1, 2, 10, 3, 4, 5] 3
Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
hour 3: data structures 101 list operations
some more functions of lists
list.remove(x): Remove the first item from the list whose value is x
list.index(x): Return the index in the list of the first item whose value is x.
list.count(x): Return the number of times x appears in the list.
list.reverse(): Reverses the list in place
list.sort(): Sorts the list in place in ascending order. For descending order, do
list.sort(reverse = True)
Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
hour 3: data structures 101 list operations
some more functions of lists
list.remove(x): Remove the first item from the list whose value is x
list.index(x): Return the index in the list of the first item whose value is x.
list.count(x): Return the number of times x appears in the list.
list.reverse(): Reverses the list in place
list.sort(): Sorts the list in place in ascending order. For descending order, do
list.sort(reverse = True)
Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
hour 3: data structures 101 list operations
some more functions of lists
list.remove(x): Remove the first item from the list whose value is x
list.index(x): Return the index in the list of the first item whose value is x.
list.count(x): Return the number of times x appears in the list.
list.reverse(): Reverses the list in place
list.sort(): Sorts the list in place in ascending order. For descending order, do
list.sort(reverse = True)
Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
hour 3: data structures 101 list operations
some more functions of lists
list.remove(x): Remove the first item from the list whose value is x
list.index(x): Return the index in the list of the first item whose value is x.
list.count(x): Return the number of times x appears in the list.
list.reverse(): Reverses the list in place
list.sort(): Sorts the list in place in ascending order. For descending order, do
list.sort(reverse = True)
Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
hour 3: data structures 101 list operations
some more functions of lists
list.remove(x): Remove the first item from the list whose value is x
list.index(x): Return the index in the list of the first item whose value is x.
list.count(x): Return the number of times x appears in the list.
list.reverse(): Reverses the list in place
list.sort(): Sorts the list in place in ascending order. For descending order, do
list.sort(reverse = True)
Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
hour 3: data structures 101 list comprehension
list comprehension and range()
range() works exactly in the same fashion as xrange(), just with one difference; range()
produces a list with all the elements in the sequence
>>> l = range(2, 10, 3)
>>> print l
[2, 5, 8]
List comprehensions are a short-hand way of making lists
>>> squares = [] >>> squares = [x ** 2 for x in xrange(6)]
>>> for x in xrange(6): >>> print squares
squares.append(x ** 2) [0, 1, 4, 9, 16, 25]
>>> print squares
[0, 1, 4, 9, 16, 25]
Satyaki Sikdar© Programming in Python April 22 2016 62 / 137
hour 3: data structures 101 list comprehension
list comprehension and range()
range() works exactly in the same fashion as xrange(), just with one difference; range()
produces a list with all the elements in the sequence
>>> l = range(2, 10, 3)
>>> print l
[2, 5, 8]
List comprehensions are a short-hand way of making lists
>>> squares = [] >>> squares = [x ** 2 for x in xrange(6)]
>>> for x in xrange(6): >>> print squares
squares.append(x ** 2) [0, 1, 4, 9, 16, 25]
>>> print squares
[0, 1, 4, 9, 16, 25]
Satyaki Sikdar© Programming in Python April 22 2016 62 / 137
hour 3: data structures 101 tuples
A tuple is a sequence of values. Enclosed by parentheses
The values can be any type, and they are indexed by integers, so, tuples are a lot like lists
However, tuples are immutable
>>> t = 'a', 'b', 'c', 'd', 'e'
>>> print t
('a', 'b', 'c', 'd', 'e')
>>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise
>>> t2 = 'a', #to create a tuple with one element, use the comma
>>> print t2
('a')
Another way to create a tuple is the built-in function tuple
>>> t = tuple() >>> t1 = tuple('dutch')
>>> print t >>> print t1
() ('d', 'u', 't', 'c', 'h')
Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
hour 3: data structures 101 tuples
A tuple is a sequence of values. Enclosed by parentheses
The values can be any type, and they are indexed by integers, so, tuples are a lot like lists
However, tuples are immutable
>>> t = 'a', 'b', 'c', 'd', 'e'
>>> print t
('a', 'b', 'c', 'd', 'e')
>>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise
>>> t2 = 'a', #to create a tuple with one element, use the comma
>>> print t2
('a')
Another way to create a tuple is the built-in function tuple
>>> t = tuple() >>> t1 = tuple('dutch')
>>> print t >>> print t1
() ('d', 'u', 't', 'c', 'h')
Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
hour 3: data structures 101 tuples
A tuple is a sequence of values. Enclosed by parentheses
The values can be any type, and they are indexed by integers, so, tuples are a lot like lists
However, tuples are immutable
>>> t = 'a', 'b', 'c', 'd', 'e'
>>> print t
('a', 'b', 'c', 'd', 'e')
>>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise
>>> t2 = 'a', #to create a tuple with one element, use the comma
>>> print t2
('a')
Another way to create a tuple is the built-in function tuple
>>> t = tuple() >>> t1 = tuple('dutch')
>>> print t >>> print t1
() ('d', 'u', 't', 'c', 'h')
Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
hour 3: data structures 101 tuples
A tuple is a sequence of values. Enclosed by parentheses
The values can be any type, and they are indexed by integers, so, tuples are a lot like lists
However, tuples are immutable
>>> t = 'a', 'b', 'c', 'd', 'e'
>>> print t
('a', 'b', 'c', 'd', 'e')
>>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise
>>> t2 = 'a', #to create a tuple with one element, use the comma
>>> print t2
('a')
Another way to create a tuple is the built-in function tuple
>>> t = tuple() >>> t1 = tuple('dutch')
>>> print t >>> print t1
() ('d', 'u', 't', 'c', 'h')
Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
hour 3: data structures 101 tuple operations
Most list operators also work on tuples. The bracket operator indexes an element
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
a
Slice operator selects a range of elements.
>>> print t[1: 3]
('b', 'c')
Try to modify one of the elements of the tuple, you get an error
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
hour 3: data structures 101 tuple operations
Most list operators also work on tuples. The bracket operator indexes an element
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
a
Slice operator selects a range of elements.
>>> print t[1: 3]
('b', 'c')
Try to modify one of the elements of the tuple, you get an error
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
hour 3: data structures 101 tuple operations
Most list operators also work on tuples. The bracket operator indexes an element
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
a
Slice operator selects a range of elements.
>>> print t[1: 3]
('b', 'c')
Try to modify one of the elements of the tuple, you get an error
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
hour 3: data structures 101 tuple operations
packing and unpacking tuples
With conventional assignments, you have to use a temp variable
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant
>>> a, b = b, a
The left side is a tuple of variables, the right side is a tuple of expressions
The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
hour 3: data structures 101 tuple operations
packing and unpacking tuples
With conventional assignments, you have to use a temp variable
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant
>>> a, b = b, a
The left side is a tuple of variables, the right side is a tuple of expressions
The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
hour 3: data structures 101 tuple operations
packing and unpacking tuples
With conventional assignments, you have to use a temp variable
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant
>>> a, b = b, a
The left side is a tuple of variables, the right side is a tuple of expressions
The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
hour 3: data structures 101 tuple operations
packing and unpacking tuples
With conventional assignments, you have to use a temp variable
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant
>>> a, b = b, a
The left side is a tuple of variables, the right side is a tuple of expressions
The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
hour 3: data structures 101 tuple operations
lists and tuples
zip takes two or more sequences and “zips” them into a list of tuples where each tuple
contains one element from each sequence
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a, 0), ('b', 1), ('c', 2)]
If the sequences are not the same length, the result has the length of the shorter one
>>> zip('Ned', 'Sansa', 'Bran')
[('N', 'S', 'B'), ('e', 'a', 'r'), ('d', 'n', 'a')]
Satyaki Sikdar© Programming in Python April 22 2016 66 / 137
hour 3: data structures 101 tuple operations
lists and tuples
zip takes two or more sequences and “zips” them into a list of tuples where each tuple
contains one element from each sequence
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a, 0), ('b', 1), ('c', 2)]
If the sequences are not the same length, the result has the length of the shorter one
>>> zip('Ned', 'Sansa', 'Bran')
[('N', 'S', 'B'), ('e', 'a', 'r'), ('d', 'n', 'a')]
Satyaki Sikdar© Programming in Python April 22 2016 66 / 137
hour 3: data structures 101 tuple operations
You can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter
0 a
1 b
2 c
Combine zip, for and tuple assignment to traverse two (or more) sequences
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
To traverse the elements of a sequence and their indices, use enumerate:
>>> for idx, ele in enumerate('abc'):
print idx, ele
Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
hour 3: data structures 101 tuple operations
You can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter
0 a
1 b
2 c
Combine zip, for and tuple assignment to traverse two (or more) sequences
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
To traverse the elements of a sequence and their indices, use enumerate:
>>> for idx, ele in enumerate('abc'):
print idx, ele
Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
hour 3: data structures 101 tuple operations
You can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter
0 a
1 b
2 c
Combine zip, for and tuple assignment to traverse two (or more) sequences
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
To traverse the elements of a sequence and their indices, use enumerate:
>>> for idx, ele in enumerate('abc'):
print idx, ele
Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
hour 3: data structures 101 tuple operations
tuple comparisons
The relational operators work with tuples and other seqs
Python starts by comparing the first element from each seq. If they are equal, it goes on
to the next elements, and so on
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
The sort function works the same way
>>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)]
>>> l.sort()
>>> print l
[(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)]
Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
hour 3: data structures 101 tuple operations
tuple comparisons
The relational operators work with tuples and other seqs
Python starts by comparing the first element from each seq. If they are equal, it goes on
to the next elements, and so on
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
The sort function works the same way
>>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)]
>>> l.sort()
>>> print l
[(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)]
Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
hour 3: data structures 101 tuple operations
tuple comparisons
The relational operators work with tuples and other seqs
Python starts by comparing the first element from each seq. If they are equal, it goes on
to the next elements, and so on
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
The sort function works the same way
>>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)]
>>> l.sort()
>>> print l
[(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)]
Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
hour 3: data structures 101 functions
functions
We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and
so on..
Python allows you to make your own functions! YAY!
Each function definition is of the form
def name of function (list_of_parameters):
body of the function
return things
A function can return things too! And in Python, every function returns something. You
can tell the function to return something that you want! By default it’s None
Notice there’s no mention of the return type
Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
hour 3: data structures 101 functions
functions
We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and
so on..
Python allows you to make your own functions! YAY!
Each function definition is of the form
def name of function (list_of_parameters):
body of the function
return things
A function can return things too! And in Python, every function returns something. You
can tell the function to return something that you want! By default it’s None
Notice there’s no mention of the return type
Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
hour 3: data structures 101 functions
functions
We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and
so on..
Python allows you to make your own functions! YAY!
Each function definition is of the form
def name of function (list_of_parameters):
body of the function
return things
A function can return things too! And in Python, every function returns something. You
can tell the function to return something that you want! By default it’s None
Notice there’s no mention of the return type
Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
hour 3: data structures 101 functions
functions
We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and
so on..
Python allows you to make your own functions! YAY!
Each function definition is of the form
def name of function (list_of_parameters):
body of the function
return things
A function can return things too! And in Python, every function returns something. You
can tell the function to return something that you want! By default it’s None
Notice there’s no mention of the return type
Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
hour 3: data structures 101 functions
functions
We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and
so on..
Python allows you to make your own functions! YAY!
Each function definition is of the form
def name of function (list_of_parameters):
body of the function
return things
A function can return things too! And in Python, every function returns something. You
can tell the function to return something that you want! By default it’s None
Notice there’s no mention of the return type
Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
hour 3: data structures 101 an example
An easy example
def maximum(x, y):
'''
returns the maximum of the two arguments
'''
if x > y:
return x
else:
return y
>>> print maximum(10, 20)
20
A function can have any name (barring the reserved words)
x and y are called formal parameters. The values (10, 20) are called actual parameters.
Function calls expect you to feed in the arguments, throws a nasty TypeError otherwise
Satyaki Sikdar© Programming in Python April 22 2016 70 / 137
hour 3: data structures 101 an example
An easy example
def maximum(x, y):
'''
returns the maximum of the two arguments
'''
if x > y:
return x
else:
return y
>>> print maximum(10, 20)
20
A function can have any name (barring the reserved words)
x and y are called formal parameters. The values (10, 20) are called actual parameters.
Function calls expect you to feed in the arguments, throws a nasty TypeError otherwise
Satyaki Sikdar© Programming in Python April 22 2016 70 / 137
hour 3: data structures 101 flow of control
flow of control in a function
1 The expressions that make up the actual parameters are evaluated. If the call is
maximum(5 + 7, 7 * 2), the arguments are evaluated first
2 The point of execution moves to the first line of the function
3 The code in the body of the function is executed until a return statement is encountered
or when there are no more lines to execute in the function body
4 The value of invocation is returned back to the point of calling
5 The point of execution transfers back to the point of invocation
It’s up to the user to use the value that’s returned.
Satyaki Sikdar© Programming in Python April 22 2016 71 / 137
hour 3: data structures 101 keyword arguments
Arguments and default values
There are two ways how formal parameters get bound to actual parameters
1 Positional: the first formal parameter is bound to the actual parameter, the second formal
to the second actual and so on
2 Keyword arguments: formals are bound to actuals using the name of the formal
parameter
def print_name(first_name, last_name, reverse):
if reverse:
print last_name + ', ' + first_name
else:
print first_name, last_name
>>> print_name('Hugh', 'Jackman', False) #prints Hugh Jackman
>>> print_name('Hugh', 'Jackman', reverse = False)
>>> print_name('Hugh', last_name = 'Jackman', reverse = False)
Satyaki Sikdar© Programming in Python April 22 2016 72 / 137
hour 3: data structures 101 keyword arguments
arguments contd.
The order of the keyword arguments does not matter. So, print_name(last_name =
’Jackman’, first_name = ’Hugh’, reverse = False) is valid
But, you can’t follow up a keyword argument with a non keyword argument. That
confuses the interpreter, and it throws an error. So, print_name(first_name = ’Hugh’,
’Jackman’, False) is not valid
Satyaki Sikdar© Programming in Python April 22 2016 73 / 137
hour 3: data structures 101 keyword arguments
arguments contd.
The order of the keyword arguments does not matter. So, print_name(last_name =
’Jackman’, first_name = ’Hugh’, reverse = False) is valid
But, you can’t follow up a keyword argument with a non keyword argument. That
confuses the interpreter, and it throws an error. So, print_name(first_name = ’Hugh’,
’Jackman’, False) is not valid
Satyaki Sikdar© Programming in Python April 22 2016 73 / 137
hour 3: data structures 101 scope
scope of variables in functions
def f(x): #x is a formal parameter
y = 1
x = x + y
print 'x = ', x
return x
>>> x = 3
>>> y = 2
>>> z = f(x) #x is an actual parameter
>>> print ';z = %s, x = %s, y = %s' % (z, x, y)
x = 4; z = 4, x = 3, y = 2
Satyaki Sikdar© Programming in Python April 22 2016 74 / 137
hour 3: data structures 101 scope
so what’s going on here?
Surely, x is surely misbehaving?! Or is it?
the two x’s are not really the same! They might have the same name, but they are
different!
Kinda like how you find someone on facebook with your name but then that person has
nothing to do with you!
The concept of name space comes into play
The variables in the function f exist only when f is executing. When the control returns
back from the function, it goes back to the variables defined previously.
Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
hour 3: data structures 101 scope
so what’s going on here?
Surely, x is surely misbehaving?! Or is it?
the two x’s are not really the same! They might have the same name, but they are
different!
Kinda like how you find someone on facebook with your name but then that person has
nothing to do with you!
The concept of name space comes into play
The variables in the function f exist only when f is executing. When the control returns
back from the function, it goes back to the variables defined previously.
Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
hour 3: data structures 101 scope
so what’s going on here?
Surely, x is surely misbehaving?! Or is it?
the two x’s are not really the same! They might have the same name, but they are
different!
Kinda like how you find someone on facebook with your name but then that person has
nothing to do with you!
The concept of name space comes into play
The variables in the function f exist only when f is executing. When the control returns
back from the function, it goes back to the variables defined previously.
Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
hour 3: data structures 101 scope
so what’s going on here?
Surely, x is surely misbehaving?! Or is it?
the two x’s are not really the same! They might have the same name, but they are
different!
Kinda like how you find someone on facebook with your name but then that person has
nothing to do with you!
The concept of name space comes into play
The variables in the function f exist only when f is executing. When the control returns
back from the function, it goes back to the variables defined previously.
Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
hour 3: data structures 101 scope
returning a bunch of things
Python allows functions to return more than one thing
def funky_func(x):
return x ** 2, x ** 3
>>> funky_func(3)
(9, 27) #things are returned as a tuple
>>> a, b = funky_func(3) #unpacking the tuple
>>> print a
9
>>> print b
27
This paradigm, though simple, is very powerful
Satyaki Sikdar© Programming in Python April 22 2016 76 / 137
hour 3: data structures 101 scope
returning a bunch of things
Python allows functions to return more than one thing
def funky_func(x):
return x ** 2, x ** 3
>>> funky_func(3)
(9, 27) #things are returned as a tuple
>>> a, b = funky_func(3) #unpacking the tuple
>>> print a
9
>>> print b
27
This paradigm, though simple, is very powerful
Satyaki Sikdar© Programming in Python April 22 2016 76 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 sets
set
A set is an unordered collection of distinct, immutable values
{ Alice , 3.1415, Carol } is a set of 3 elements
{ Dean } is a singleton set
>>> cset = {11, 11, 22}
>>> cset
set([11, 22])
Sets are mutable - can add or remove things on the fly
Insertion using add
Deletion using remove or discard
>>> st = {'Jon', 'Arya'}
>>> st.add('Jaime') >>> st.remove('Jon')
>>> print st >>> print st
set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])
Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
hour 3: data structures 101 set operations
set operations
Sets in Python support all common set operations
>>> test_team = {'Cook', 'Root', 'Stokes', 'Ali', 'Broad'}
>>> odi_team = {'Hales', 'Roy', 'Root', 'Ali', 'Stokes'}
>>>
>>> print test_team | odi_team #set union
set(['Stokes', 'Hales', 'Ali', 'Broad', 'Roy', 'Cook', 'Root'])
>>> print test_team & odi_team #set intersection
set(['Stokes', 'Root', 'Ali'])
>>> test_team - odi_team #set differnce
set(['Cook', 'Broad'])
>>> test_team ^ odi_team #symmetric difference
set(['Hales', 'Broad', 'Roy', 'Cook'])
Satyaki Sikdar© Programming in Python April 22 2016 78 / 137
hour 3: data structures 101 set operations
set operations
Sets do not support indexing!
>>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'}
>>> myset
set(['Toronto', 'Amsterdam', 'Winnipeg'])
>>> myset[0]
TypeError: 'set' object does not support indexing
+ operator doesn’t work with sets
>>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'}
>>> myset2 = {'Brussels', 'Hamilton'}
>>> myset1 + myset2
TypeError: unsupported operand type(s) for +: 'set' and 'set'
Satyaki Sikdar© Programming in Python April 22 2016 79 / 137
hour 3: data structures 101 set operations
set operations
Sets do not support indexing!
>>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'}
>>> myset
set(['Toronto', 'Amsterdam', 'Winnipeg'])
>>> myset[0]
TypeError: 'set' object does not support indexing
+ operator doesn’t work with sets
>>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'}
>>> myset2 = {'Brussels', 'Hamilton'}
>>> myset1 + myset2
TypeError: unsupported operand type(s) for +: 'set' and 'set'
Satyaki Sikdar© Programming in Python April 22 2016 79 / 137
hour 3: data structures 101 dictionaries
dictionary
A dictionary is like a list, but more general - a personal favorite
In a list, the indices have to be integers; in a dictionary they can be (almost) any type
The keys must be immutable
Let’s build a dictionary that maps from English to Spanish words. Keys and values are
both strings
>>> eng2sp = dict() # or eng2sp = {}
>>> print eng2sp
{}
Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
hour 3: data structures 101 dictionaries
dictionary
A dictionary is like a list, but more general - a personal favorite
In a list, the indices have to be integers; in a dictionary they can be (almost) any type
The keys must be immutable
Let’s build a dictionary that maps from English to Spanish words. Keys and values are
both strings
>>> eng2sp = dict() # or eng2sp = {}
>>> print eng2sp
{}
Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
hour 3: data structures 101 dictionaries
dictionary
A dictionary is like a list, but more general - a personal favorite
In a list, the indices have to be integers; in a dictionary they can be (almost) any type
The keys must be immutable
Let’s build a dictionary that maps from English to Spanish words. Keys and values are
both strings
>>> eng2sp = dict() # or eng2sp = {}
>>> print eng2sp
{}
Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
hour 3: data structures 101 dictionaries
dictionary
A dictionary is like a list, but more general - a personal favorite
In a list, the indices have to be integers; in a dictionary they can be (almost) any type
The keys must be immutable
Let’s build a dictionary that maps from English to Spanish words. Keys and values are
both strings
>>> eng2sp = dict() # or eng2sp = {}
>>> print eng2sp
{}
Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
hour 3: data structures 101 dictionary manipulations
To add items to the dictionary, use square brackets
>>> eng2sp['one'] = 'uno'
Creates an item that maps from the key ’one’ to the value ’uno’
>>> print eng2sp
{'one': 'uno'}
Instantiate a dictionary with multiple items like
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of key-value pairs is not the same
Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
hour 3: data structures 101 dictionary manipulations
To add items to the dictionary, use square brackets
>>> eng2sp['one'] = 'uno'
Creates an item that maps from the key ’one’ to the value ’uno’
>>> print eng2sp
{'one': 'uno'}
Instantiate a dictionary with multiple items like
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of key-value pairs is not the same
Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
hour 3: data structures 101 dictionary manipulations
To add items to the dictionary, use square brackets
>>> eng2sp['one'] = 'uno'
Creates an item that maps from the key ’one’ to the value ’uno’
>>> print eng2sp
{'one': 'uno'}
Instantiate a dictionary with multiple items like
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of key-value pairs is not the same
Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
hour 3: data structures 101 dictionary manipulations
To add items to the dictionary, use square brackets
>>> eng2sp['one'] = 'uno'
Creates an item that maps from the key ’one’ to the value ’uno’
>>> print eng2sp
{'one': 'uno'}
Instantiate a dictionary with multiple items like
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of key-value pairs is not the same
Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
hour 3: data structures 101 dictionary manipulations
constraints on keys and values
Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys
Ints, floats, strings, tuples, frozensets are fine!
There’s no constraint on the nature of values
>>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'],
'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'],
'Greyjoy': ['Theon', 'Yara', 'Balon']}
>>> print house_members['Greyjoy']
['Theon', 'Yara', 'Balon']
Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
hour 3: data structures 101 dictionary manipulations
constraints on keys and values
Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys
Ints, floats, strings, tuples, frozensets are fine!
There’s no constraint on the nature of values
>>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'],
'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'],
'Greyjoy': ['Theon', 'Yara', 'Balon']}
>>> print house_members['Greyjoy']
['Theon', 'Yara', 'Balon']
Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
hour 3: data structures 101 dictionary manipulations
constraints on keys and values
Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys
Ints, floats, strings, tuples, frozensets are fine!
There’s no constraint on the nature of values
>>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'],
'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'],
'Greyjoy': ['Theon', 'Yara', 'Balon']}
>>> print house_members['Greyjoy']
['Theon', 'Yara', 'Balon']
Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
hour 3: data structures 101 dictionary manipulations
Indexing is done solely using the keys
>>> print eng2sp['two']
dos
If the key isn’t in the dictionary, you get an exception
>>> print eng2sp['four']
KeyError: 'four'
len function returns the number of key-value pairs
>>> len(eng2sp)
3
in tells you whether something appears as a key in the dictionary (appearing as a value is
not good enough)
>>> 'one' in eng2sp >>> 'uno' in eng2sp
True False
Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
hour 3: data structures 101 dictionary manipulations
Indexing is done solely using the keys
>>> print eng2sp['two']
dos
If the key isn’t in the dictionary, you get an exception
>>> print eng2sp['four']
KeyError: 'four'
len function returns the number of key-value pairs
>>> len(eng2sp)
3
in tells you whether something appears as a key in the dictionary (appearing as a value is
not good enough)
>>> 'one' in eng2sp >>> 'uno' in eng2sp
True False
Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
hour 3: data structures 101 dictionary manipulations
Indexing is done solely using the keys
>>> print eng2sp['two']
dos
If the key isn’t in the dictionary, you get an exception
>>> print eng2sp['four']
KeyError: 'four'
len function returns the number of key-value pairs
>>> len(eng2sp)
3
in tells you whether something appears as a key in the dictionary (appearing as a value is
not good enough)
>>> 'one' in eng2sp >>> 'uno' in eng2sp
True False
Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
hour 3: data structures 101 dictionary manipulations
Indexing is done solely using the keys
>>> print eng2sp['two']
dos
If the key isn’t in the dictionary, you get an exception
>>> print eng2sp['four']
KeyError: 'four'
len function returns the number of key-value pairs
>>> len(eng2sp)
3
in tells you whether something appears as a key in the dictionary (appearing as a value is
not good enough)
>>> 'one' in eng2sp >>> 'uno' in eng2sp
True False
Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
hour 3: data structures 101 dictionary manipulations
deleting things
A specific key can be deleted from a dictionary by using pop
>>> eng2sp
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> eng2sp.pop('two')
'dos'
>>> eng2sp
{'one': 'uno', 'three': 'tres'}
A key at random can be deleted by using popitem
>>> eng2sp
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> eng2sp.popitem()
('three', 'tres')
Satyaki Sikdar© Programming in Python April 22 2016 84 / 137
hour 3: data structures 101 dictionary manipulations
deleting things
A specific key can be deleted from a dictionary by using pop
>>> eng2sp
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> eng2sp.pop('two')
'dos'
>>> eng2sp
{'one': 'uno', 'three': 'tres'}
A key at random can be deleted by using popitem
>>> eng2sp
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> eng2sp.popitem()
('three', 'tres')
Satyaki Sikdar© Programming in Python April 22 2016 84 / 137
hour 3: data structures 101 dictionary manipulations
Dicts have a method called items that returns a list of tuples of key-value pairs
>>> d = {'a': 0, 'b': 1, 'c': 2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
Going in the other way, you can use a list of tuples to init a new dict
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way
>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
hour 3: data structures 101 dictionary manipulations
Dicts have a method called items that returns a list of tuples of key-value pairs
>>> d = {'a': 0, 'b': 1, 'c': 2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
Going in the other way, you can use a list of tuples to init a new dict
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way
>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
hour 3: data structures 101 dictionary manipulations
Dicts have a method called items that returns a list of tuples of key-value pairs
>>> d = {'a': 0, 'b': 1, 'c': 2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
Going in the other way, you can use a list of tuples to init a new dict
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way
>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
hour 3: data structures 101 counters
counters
Given a string and you want to count how many times each letter appears
1 create 26 variables, one for each letter of the alphabet
2 create a list with 26 elements. Then convert each character to a number and use it as an
index into the list
3 create a dict with characters as keys and counters as the values
def hist(st):
counter = dict()
for c in st:
if c not in counter:
counter[c] = 1
else:
counter[c] += 1
return counter
>>> print hist('brontosaurus')
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
hour 3: data structures 101 counters
counters
Given a string and you want to count how many times each letter appears
1 create 26 variables, one for each letter of the alphabet
2 create a list with 26 elements. Then convert each character to a number and use it as an
index into the list
3 create a dict with characters as keys and counters as the values
def hist(st):
counter = dict()
for c in st:
if c not in counter:
counter[c] = 1
else:
counter[c] += 1
return counter
>>> print hist('brontosaurus')
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
hour 3: data structures 101 counters
counters
Given a string and you want to count how many times each letter appears
1 create 26 variables, one for each letter of the alphabet
2 create a list with 26 elements. Then convert each character to a number and use it as an
index into the list
3 create a dict with characters as keys and counters as the values
def hist(st):
counter = dict()
for c in st:
if c not in counter:
counter[c] = 1
else:
counter[c] += 1
return counter
>>> print hist('brontosaurus')
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
hour 3: data structures 101 counters
counters
Given a string and you want to count how many times each letter appears
1 create 26 variables, one for each letter of the alphabet
2 create a list with 26 elements. Then convert each character to a number and use it as an
index into the list
3 create a dict with characters as keys and counters as the values
def hist(st):
counter = dict()
for c in st:
if c not in counter:
counter[c] = 1
else:
counter[c] += 1
return counter
>>> print hist('brontosaurus')
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
hour 3: data structures 101 counters
inverting a dictionary
Given a dict that maps letters to freq, create a dict that maps freq to letters
Several letters may have the same freq, so each value must be a list
def inv_dict(d):
inv = {}
for key in d:
val = d[key]
if val not in inv: #we haven't seen the value so far
inv[val] = [key]
else:
inv[val].append(key)
return val
>>> h = hist('parrot') >>> print inv_dict(h)
>>> print h {1: ['a', 'p', 't', 'o'], 2: ['r']}
{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}
Satyaki Sikdar© Programming in Python April 22 2016 87 / 137
hour 3: data structures 101 counters
inverting a dictionary
Given a dict that maps letters to freq, create a dict that maps freq to letters
Several letters may have the same freq, so each value must be a list
def inv_dict(d):
inv = {}
for key in d:
val = d[key]
if val not in inv: #we haven't seen the value so far
inv[val] = [key]
else:
inv[val].append(key)
return val
>>> h = hist('parrot') >>> print inv_dict(h)
>>> print h {1: ['a', 'p', 't', 'o'], 2: ['r']}
{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}
Satyaki Sikdar© Programming in Python April 22 2016 87 / 137
hour 4: confusion 101 recursion
Satyaki Sikdar© Programming in Python April 22 2016 88 / 137
hour 4: confusion 101 introduction
what is it anyway?
It’s a method where the solution to a problem depends on solutions to smaller instances of
the same problem
Some problems are inherently recursive Let’s see an example. The legal code of the US
defines a natural born citizen roughly as follows:
Any child born inside the United States
Any child born in wedlock outside the United States both of whose parents are citizens of the
US, as long as one parent has lived in the US prior to the birth of the child, and
Any child born in wedlock outside the US one of whose parents is a US citizen who has lived
at least five years, .... so on
Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
hour 4: confusion 101 introduction
what is it anyway?
It’s a method where the solution to a problem depends on solutions to smaller instances of
the same problem
Some problems are inherently recursive Let’s see an example. The legal code of the US
defines a natural born citizen roughly as follows:
Any child born inside the United States
Any child born in wedlock outside the United States both of whose parents are citizens of the
US, as long as one parent has lived in the US prior to the birth of the child, and
Any child born in wedlock outside the US one of whose parents is a US citizen who has lived
at least five years, .... so on
Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
hour 4: confusion 101 introduction
what is it anyway?
It’s a method where the solution to a problem depends on solutions to smaller instances of
the same problem
Some problems are inherently recursive Let’s see an example. The legal code of the US
defines a natural born citizen roughly as follows:
Any child born inside the United States
Any child born in wedlock outside the United States both of whose parents are citizens of the
US, as long as one parent has lived in the US prior to the birth of the child, and
Any child born in wedlock outside the US one of whose parents is a US citizen who has lived
at least five years, .... so on
Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
hour 4: confusion 101 introduction
what is it anyway?
It’s a method where the solution to a problem depends on solutions to smaller instances of
the same problem
Some problems are inherently recursive Let’s see an example. The legal code of the US
defines a natural born citizen roughly as follows:
Any child born inside the United States
Any child born in wedlock outside the United States both of whose parents are citizens of the
US, as long as one parent has lived in the US prior to the birth of the child, and
Any child born in wedlock outside the US one of whose parents is a US citizen who has lived
at least five years, .... so on
Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
hour 4: confusion 101 introduction
what is it anyway?
It’s a method where the solution to a problem depends on solutions to smaller instances of
the same problem
Some problems are inherently recursive Let’s see an example. The legal code of the US
defines a natural born citizen roughly as follows:
Any child born inside the United States
Any child born in wedlock outside the United States both of whose parents are citizens of the
US, as long as one parent has lived in the US prior to the birth of the child, and
Any child born in wedlock outside the US one of whose parents is a US citizen who has lived
at least five years, .... so on
Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
hour 4: confusion 101 the structure
The structure of a generic recursive code
def rec_function(parameters):
if bool_expr1: # base case 1
return something
if bool_expr2: # base case 2
return something_else
do_something_funky
inductive_case #call rec_function() with reduced parameters
IMPORTANT:
1 The base cases must terminate the flow of code and return something meaningful
2 The inductive case must be called for the reduced problem, such that it reaches the base
case sometime
Satyaki Sikdar© Programming in Python April 22 2016 90 / 137
hour 4: confusion 101 illustrations
example 1
Mathematically,
n! =
n ∗ (n − 1)! if n > 1
1 otherwise
def factR(n):
'''
computes n! recursively
n >=0
'''
if n <= 1:
return 1
else:
return n * factorial(n - 1)
def factI(n):
'''
computes n! iteratively
n >=0
'''
result = 1
while n > 1:
result = result * n
n -= 1
return result
Satyaki Sikdar© Programming in Python April 22 2016 91 / 137
hour 4: confusion 101 illustrations
how does it work?
Say you are calling factorial(3). Let’s see what happens!
factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)
factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)
factorial(1) is called. Hits the base case! No further calls to factorial. Time to track
back. factorial(1) returns 1
factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)
returns 2 x 1
factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3
x 2 => 6 And we are done!
Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
hour 4: confusion 101 illustrations
how does it work?
Say you are calling factorial(3). Let’s see what happens!
factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)
factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)
factorial(1) is called. Hits the base case! No further calls to factorial. Time to track
back. factorial(1) returns 1
factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)
returns 2 x 1
factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3
x 2 => 6 And we are done!
Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
hour 4: confusion 101 illustrations
how does it work?
Say you are calling factorial(3). Let’s see what happens!
factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)
factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)
factorial(1) is called. Hits the base case! No further calls to factorial. Time to track
back. factorial(1) returns 1
factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)
returns 2 x 1
factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3
x 2 => 6 And we are done!
Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
hour 4: confusion 101 illustrations
how does it work?
Say you are calling factorial(3). Let’s see what happens!
factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)
factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)
factorial(1) is called. Hits the base case! No further calls to factorial. Time to track
back. factorial(1) returns 1
factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)
returns 2 x 1
factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3
x 2 => 6 And we are done!
Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
hour 4: confusion 101 illustrations
how does it work?
Say you are calling factorial(3). Let’s see what happens!
factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)
factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)
factorial(1) is called. Hits the base case! No further calls to factorial. Time to track
back. factorial(1) returns 1
factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)
returns 2 x 1
factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3
x 2 => 6 And we are done!
Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
hour 4: confusion 101 recursion woes
base cases gone wrong!
n! =
(n+1)!
n+1 if n > 0
1 otherwise
Although this seems valid, but there lies a problem. Look at the base case! Will it ever be
reached? If we implement this function, we will get a run time error. Let’s see what it is.
Satyaki Sikdar© Programming in Python April 22 2016 93 / 137
hour 4: confusion 101 recursion woes
implementation
def factorial(n):
if n == 0:
return 1
else:
return factorial(n + 1) / (n + 1)
>>> factorial(4) => Something nasty!
RuntimeError: maximum recursion depth exceeded
It’s no surprise that factorial(4) fails. The same thing happens whenever the argument is
non zero.
So, who’s to blame? The innocent looking recurrence relation? Yeah
Satyaki Sikdar© Programming in Python April 22 2016 94 / 137
hour 4: confusion 101 recursion woes
implementation
def factorial(n):
if n == 0:
return 1
else:
return factorial(n + 1) / (n + 1)
>>> factorial(4) => Something nasty!
RuntimeError: maximum recursion depth exceeded
It’s no surprise that factorial(4) fails. The same thing happens whenever the argument is
non zero.
So, who’s to blame? The innocent looking recurrence relation? Yeah
Satyaki Sikdar© Programming in Python April 22 2016 94 / 137
hour 4: confusion 101 recursion woes
how to fix this mess?!
Can the base case ever be reached with n > 0 ? NO!
So, as a consequence, the program doesn’t stop until you run out of stack space!
Stack overflow is the recursive equivalent to an infinite loop in iteration
Fix the recurrence relation to get the correct results.
Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
hour 4: confusion 101 recursion woes
how to fix this mess?!
Can the base case ever be reached with n > 0 ? NO!
So, as a consequence, the program doesn’t stop until you run out of stack space!
Stack overflow is the recursive equivalent to an infinite loop in iteration
Fix the recurrence relation to get the correct results.
Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
hour 4: confusion 101 recursion woes
how to fix this mess?!
Can the base case ever be reached with n > 0 ? NO!
So, as a consequence, the program doesn’t stop until you run out of stack space!
Stack overflow is the recursive equivalent to an infinite loop in iteration
Fix the recurrence relation to get the correct results.
Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
hour 4: confusion 101 recursion woes
how to fix this mess?!
Can the base case ever be reached with n > 0 ? NO!
So, as a consequence, the program doesn’t stop until you run out of stack space!
Stack overflow is the recursive equivalent to an infinite loop in iteration
Fix the recurrence relation to get the correct results.
Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
they breed like bunnies!
Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible
assumptions
The assumptions
Bunnies are able to mate when they are 1 month old
They have a 1 month gestation period
They are immortal
Each female gives birth to one male and one female bunnies
every time
Two bunnies, a male and a female are put in an exhibit
The question is, how many pregnant bunnies would there be
at the end of say n months?
Month n Females Fn
0 1
1 1
2 2
3 3
4 5
5 8
6 13
Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
hour 4: confusion 101 fibonacci numbers
Fibonacci numbers
Fn =



Fn−1 + Fn−2 n 2
1 n = 1
0 n = 0
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n - 1) + fibo(n - 2)
Satyaki Sikdar© Programming in Python April 22 2016 97 / 137
hour 4: confusion 101 recursion tree
recursion tree
Figure: Recursion tree for fib(7)
Satyaki Sikdar© Programming in Python April 22 2016 98 / 137
hour 4: confusion 101 speeding up
speed of computation
Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?
Let’s take another look at the recursion tree
Aren’t we doing the same calculations in between? Is there a better way? Hell yeah!
Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
hour 4: confusion 101 speeding up
speed of computation
Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?
Let’s take another look at the recursion tree
Aren’t we doing the same calculations in between? Is there a better way? Hell yeah!
Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
hour 4: confusion 101 speeding up
speed of computation
Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?
Let’s take another look at the recursion tree
Aren’t we doing the same calculations in between? Is there a better way? Hell yeah!
Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
hour 4: confusion 101 speeding up
a bottom-up approach
def fib_v2(n):
ans = [0, 1]
for i in xrange(2, n + 1):
ans.append(ans[i - 1] + ans[i - 2])
return ans[n]
Is this approach better? YES!
Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2
calls to the ans list.
Try calculating the 40th Fibonacci number again! Much faster, isn’t it?
Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
hour 4: confusion 101 speeding up
a bottom-up approach
def fib_v2(n):
ans = [0, 1]
for i in xrange(2, n + 1):
ans.append(ans[i - 1] + ans[i - 2])
return ans[n]
Is this approach better? YES!
Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2
calls to the ans list.
Try calculating the 40th Fibonacci number again! Much faster, isn’t it?
Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
hour 4: confusion 101 speeding up
a bottom-up approach
def fib_v2(n):
ans = [0, 1]
for i in xrange(2, n + 1):
ans.append(ans[i - 1] + ans[i - 2])
return ans[n]
Is this approach better? YES!
Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2
calls to the ans list.
Try calculating the 40th Fibonacci number again! Much faster, isn’t it?
Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy intro to OOP
object oriented programming
So far, we have seen a lot of Python’s own data structures and types. What if we need
specialized structures which are not natively provided in Py?
We have the power of defining our own type!
Let’s see an example. Say we want to represent a point in 2-D space. What are our
options?
Store the coordinates x and y in two variables x and y
Store the coordinates as elements in a list or tuple
Create a new type to represent points as specialized things called objects
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon
Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
classes
A user-defined type is also called a class. A class defintion looks like this
class Point:
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point
The body is a docstring that explains what the class is for
We can define variables and functions inside a class definition
The class is like a factory for creating objects
To create a Point, you call Point as if it were a function. It is called instantiation and the
object is an instance of the class
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
hour 5: oops-a-daisy class
attributes
You can assign values to an instance using dot notation
>>> blank.x = 3.0
>>> blank.y = 4.0
You can read the value of an attribute using the same syntax
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
Figure: Object diagram
The expression blank.x means, “Go to the object blank refers to and get the value of x”
In this case, we assign that value to a variable named x. There is no conflict between the
variable x and the attribute x
Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
hour 5: oops-a-daisy class
attributes
You can assign values to an instance using dot notation
>>> blank.x = 3.0
>>> blank.y = 4.0
You can read the value of an attribute using the same syntax
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
Figure: Object diagram
The expression blank.x means, “Go to the object blank refers to and get the value of x”
In this case, we assign that value to a variable named x. There is no conflict between the
variable x and the attribute x
Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
hour 5: oops-a-daisy class
attributes
You can assign values to an instance using dot notation
>>> blank.x = 3.0
>>> blank.y = 4.0
You can read the value of an attribute using the same syntax
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
Figure: Object diagram
The expression blank.x means, “Go to the object blank refers to and get the value of x”
In this case, we assign that value to a variable named x. There is no conflict between the
variable x and the attribute x
Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
hour 5: oops-a-daisy class
attributes
You can assign values to an instance using dot notation
>>> blank.x = 3.0
>>> blank.y = 4.0
You can read the value of an attribute using the same syntax
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
Figure: Object diagram
The expression blank.x means, “Go to the object blank refers to and get the value of x”
In this case, we assign that value to a variable named x. There is no conflict between the
variable x and the attribute x
Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
hour 5: oops-a-daisy class
If you try to access an attribute that doesn’t exist, you get an AttributeError
If you are not sure what type an object is, you can use the type function
If you are not sure whether an object has a particular attribute, you can use the built-in
function hasattr
>>> p = Point()
>>> p.x = 5.5
>>> p.y = 2.2
>>> print p.x
5.5
>>> print p.y
2.2
>>> print p.z
AttributeError: Point instance has no attribute 'z'
>>> type(p)
<type '__main__'.Point'>
>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False
Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
hour 5: oops-a-daisy class
If you try to access an attribute that doesn’t exist, you get an AttributeError
If you are not sure what type an object is, you can use the type function
If you are not sure whether an object has a particular attribute, you can use the built-in
function hasattr
>>> p = Point()
>>> p.x = 5.5
>>> p.y = 2.2
>>> print p.x
5.5
>>> print p.y
2.2
>>> print p.z
AttributeError: Point instance has no attribute 'z'
>>> type(p)
<type '__main__'.Point'>
>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False
Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
hour 5: oops-a-daisy class
If you try to access an attribute that doesn’t exist, you get an AttributeError
If you are not sure what type an object is, you can use the type function
If you are not sure whether an object has a particular attribute, you can use the built-in
function hasattr
>>> p = Point()
>>> p.x = 5.5
>>> p.y = 2.2
>>> print p.x
5.5
>>> print p.y
2.2
>>> print p.z
AttributeError: Point instance has no attribute 'z'
>>> type(p)
<type '__main__'.Point'>
>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False
Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
hour 5: oops-a-daisy manipulating objects
Dot notations are powerful. They can be used in any context
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> import math
>>> print math.sqrt(blank.x ** 2 + blank.y ** 2)
5.0
You can pass an instance as an argument in the usual way
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
print_point takes a Point as an arg and prints it in mathematical notation. To invoke it,
you pass blank as an arg
>>> print_point(blank)
(3.0, 4.0)
Inside the function, p is an alias for blank, so if the function modifies p, blank changes
Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
hour 5: oops-a-daisy manipulating objects
Dot notations are powerful. They can be used in any context
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> import math
>>> print math.sqrt(blank.x ** 2 + blank.y ** 2)
5.0
You can pass an instance as an argument in the usual way
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
print_point takes a Point as an arg and prints it in mathematical notation. To invoke it,
you pass blank as an arg
>>> print_point(blank)
(3.0, 4.0)
Inside the function, p is an alias for blank, so if the function modifies p, blank changes
Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
hour 5: oops-a-daisy manipulating objects
Dot notations are powerful. They can be used in any context
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> import math
>>> print math.sqrt(blank.x ** 2 + blank.y ** 2)
5.0
You can pass an instance as an argument in the usual way
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
print_point takes a Point as an arg and prints it in mathematical notation. To invoke it,
you pass blank as an arg
>>> print_point(blank)
(3.0, 4.0)
Inside the function, p is an alias for blank, so if the function modifies p, blank changes
Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
hour 5: oops-a-daisy manipulating objects
Dot notations are powerful. They can be used in any context
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> import math
>>> print math.sqrt(blank.x ** 2 + blank.y ** 2)
5.0
You can pass an instance as an argument in the usual way
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
print_point takes a Point as an arg and prints it in mathematical notation. To invoke it,
you pass blank as an arg
>>> print_point(blank)
(3.0, 4.0)
Inside the function, p is an alias for blank, so if the function modifies p, blank changes
Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
def dist_bw_points(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2))
Sometimes it is obvious what the attributes of an object should be, but other times you
have to make decisions
For example, imagine you are designing a class to represent rectangles. What attributes
would you use to specify the location and size of a rectangle?
There are at least two possibilities:
specify one corner of the rectangle, the width, and the height
specify two opposing corners
Following the first one, here’s an example of the class definition. Corner represents the
lower-left corner
class Rectangle:
'''Represents a rectangle.
attributes: width, height, corner.
'''
Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
hour 5: oops-a-daisy manipulating objects
To represent a rectangle, you have to instantiate a Rectangle object and assign values to
the attributes
>>> box = Rectangle()
>>> box.width = 100.0
>>> box.height = 200.0
>>> box.corner = Point()
>>> box.corner.x = 0.0
>>> box.corner.y = 0.0 Figure: Object diagram for box
The expression box.corner.x means, “Go to the object box refers to and select the
attribute named corner; then go to that object and select the attribute named x”
Satyaki Sikdar© Programming in Python April 22 2016 107 / 137
hour 5: oops-a-daisy manipulating objects
To represent a rectangle, you have to instantiate a Rectangle object and assign values to
the attributes
>>> box = Rectangle()
>>> box.width = 100.0
>>> box.height = 200.0
>>> box.corner = Point()
>>> box.corner.x = 0.0
>>> box.corner.y = 0.0 Figure: Object diagram for box
The expression box.corner.x means, “Go to the object box refers to and select the
attribute named corner; then go to that object and select the attribute named x”
Satyaki Sikdar© Programming in Python April 22 2016 107 / 137
hour 5: oops-a-daisy manipulating objects
Functions can return instances
find_center takes a Rectangle as an argument and returns a Point that contains the
coordinates of the center of the Rectangle
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width / 2.0
p.y = rect.corner.y + rect.height / 2.0
return p
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)
Satyaki Sikdar© Programming in Python April 22 2016 108 / 137
hour 5: oops-a-daisy manipulating objects
Functions can return instances
find_center takes a Rectangle as an argument and returns a Point that contains the
coordinates of the center of the Rectangle
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width / 2.0
p.y = rect.corner.y + rect.height / 2.0
return p
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)
Satyaki Sikdar© Programming in Python April 22 2016 108 / 137
hour 5: oops-a-daisy manipulating objects
You can change the state of an object by making an assignment to one of its attributes
You can also write functions that modify objects
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0
Satyaki Sikdar© Programming in Python April 22 2016 109 / 137
hour 5: oops-a-daisy manipulating objects
You can change the state of an object by making an assignment to one of its attributes
You can also write functions that modify objects
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0
Satyaki Sikdar© Programming in Python April 22 2016 109 / 137
hour 5: oops-a-daisy manipulating objects
So far, the classes have been a little boring with just the definition and a docstring. Can
we do more? Let’s find ou
class Point:
'''Represents a point in 2-D space.'''
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
>>> pt = Point()
>>> pt.x = 3.5
>>> pt.y = 0
>>> Point.print_point(pt) #less common
(3.5, 0)
>>> pt.print_point() #widely used
(3.5, 0)
class Point:
'''Represents a point in 2-D space.'
def print_point( self ):
print '(%g, %g)'%(self.x, self.y
>>> pt = Point()
>>> pt.x = 3.5
>>> pt.y = 0
>>> Point.print_point(pt) #less common
(3.5, 0)
>>> pt.print_point() #widely used
(3.5, 0)
By convention, the first arg of every function in a class is set to self
Satyaki Sikdar© Programming in Python April 22 2016 110 / 137
hour 5: oops-a-daisy manipulating objects
So far, the classes have been a little boring with just the definition and a docstring. Can
we do more? Let’s find ou
class Point:
'''Represents a point in 2-D space.'''
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
>>> pt = Point()
>>> pt.x = 3.5
>>> pt.y = 0
>>> Point.print_point(pt) #less common
(3.5, 0)
>>> pt.print_point() #widely used
(3.5, 0)
class Point:
'''Represents a point in 2-D space.'
def print_point( self ):
print '(%g, %g)'%(self.x, self.y
>>> pt = Point()
>>> pt.x = 3.5
>>> pt.y = 0
>>> Point.print_point(pt) #less common
(3.5, 0)
>>> pt.print_point() #widely used
(3.5, 0)
By convention, the first arg of every function in a class is set to self
Satyaki Sikdar© Programming in Python April 22 2016 110 / 137
hour 5: oops-a-daisy manipulating objects
There’s no upper bound of the number of functions inside a class
The first argument self is implicit, for example
class Point:
'''Represents a point in 2-D space.'''
def print_point( self ):
print '(%g, %g)'%(self.x, self.y)
def transl(self, dx, dy):
self.x += dx
self.y += dy
>>> pt = Point() >>> pt.transl(10, 20) #fine
>>> pt.x = 6.0 >>> pt.transl(10, 20, 30) #not fine
>>> pt.y = 8.0 TypeError: transl() takes exactly 3 arguments (4 given)
>>> pt.print_point()
(6.0, 8.0)
Satyaki Sikdar© Programming in Python April 22 2016 111 / 137
hour 5: oops-a-daisy manipulating objects
There’s no upper bound of the number of functions inside a class
The first argument self is implicit, for example
class Point:
'''Represents a point in 2-D space.'''
def print_point( self ):
print '(%g, %g)'%(self.x, self.y)
def transl(self, dx, dy):
self.x += dx
self.y += dy
>>> pt = Point() >>> pt.transl(10, 20) #fine
>>> pt.x = 6.0 >>> pt.transl(10, 20, 30) #not fine
>>> pt.y = 8.0 TypeError: transl() takes exactly 3 arguments (4 given)
>>> pt.print_point()
(6.0, 8.0)
Satyaki Sikdar© Programming in Python April 22 2016 111 / 137
hour 5: oops-a-daisy special methods
the init method
The init method is a special method that gets invoked when an object is created
The full name is __init__, two underbars followed by init followed by two more
underbars
The parameters for init usually have the same name as the attributes
The parameters here, are optional
#inside class Point
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
#outside the class
>>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed
>>> p1.print_point() >>> p2.print_point()
(0.0, 0.0) (2, 3.4)
Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
hour 5: oops-a-daisy special methods
the init method
The init method is a special method that gets invoked when an object is created
The full name is __init__, two underbars followed by init followed by two more
underbars
The parameters for init usually have the same name as the attributes
The parameters here, are optional
#inside class Point
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
#outside the class
>>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed
>>> p1.print_point() >>> p2.print_point()
(0.0, 0.0) (2, 3.4)
Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
hour 5: oops-a-daisy special methods
the init method
The init method is a special method that gets invoked when an object is created
The full name is __init__, two underbars followed by init followed by two more
underbars
The parameters for init usually have the same name as the attributes
The parameters here, are optional
#inside class Point
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
#outside the class
>>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed
>>> p1.print_point() >>> p2.print_point()
(0.0, 0.0) (2, 3.4)
Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
hour 5: oops-a-daisy special methods
the init method
The init method is a special method that gets invoked when an object is created
The full name is __init__, two underbars followed by init followed by two more
underbars
The parameters for init usually have the same name as the attributes
The parameters here, are optional
#inside class Point
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
#outside the class
>>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed
>>> p1.print_point() >>> p2.print_point()
(0.0, 0.0) (2, 3.4)
Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
hour 5: oops-a-daisy special methods
the str method
__str__ is a special method like __init__ and it’s supposed to return a string
representation of the object
Takes just the object as the argument
For the Point class, the str method can be like
#inside the class Point
def __str__(self): #allows you to use the print statement
return '(%g, %g)' % (self.x, self.y)
#outside the class
>>> p = Point(2.0, 3.0)
>>> print p
(2.0, 3.0)
Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
hour 5: oops-a-daisy special methods
the str method
__str__ is a special method like __init__ and it’s supposed to return a string
representation of the object
Takes just the object as the argument
For the Point class, the str method can be like
#inside the class Point
def __str__(self): #allows you to use the print statement
return '(%g, %g)' % (self.x, self.y)
#outside the class
>>> p = Point(2.0, 3.0)
>>> print p
(2.0, 3.0)
Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
hour 5: oops-a-daisy special methods
the str method
__str__ is a special method like __init__ and it’s supposed to return a string
representation of the object
Takes just the object as the argument
For the Point class, the str method can be like
#inside the class Point
def __str__(self): #allows you to use the print statement
return '(%g, %g)' % (self.x, self.y)
#outside the class
>>> p = Point(2.0, 3.0)
>>> print p
(2.0, 3.0)
Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
hour 5: oops-a-daisy special methods
the add method
__add__ is a special method like __str__ and it overloads the ’+’ operator
Takes two arguments, the caller object and another object. Returns a new object that’s
the sum of the two objects
For the Point class, the add method can be like
#inside the class Point
def __add__(self, other_pt):
new_pt = Point()
new_pt.x = self.x + other_pt.x
new_pt.y = self.y + other_pt.y
return new_pt
#outside the class
>>> p1 = Point(2.0, 3.0) >>> print p1 + p2
>>> p2 = Point(3.4, 8.2) (5.4, 11.2)
Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
hour 5: oops-a-daisy special methods
the add method
__add__ is a special method like __str__ and it overloads the ’+’ operator
Takes two arguments, the caller object and another object. Returns a new object that’s
the sum of the two objects
For the Point class, the add method can be like
#inside the class Point
def __add__(self, other_pt):
new_pt = Point()
new_pt.x = self.x + other_pt.x
new_pt.y = self.y + other_pt.y
return new_pt
#outside the class
>>> p1 = Point(2.0, 3.0) >>> print p1 + p2
>>> p2 = Point(3.4, 8.2) (5.4, 11.2)
Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
hour 5: oops-a-daisy special methods
the add method
__add__ is a special method like __str__ and it overloads the ’+’ operator
Takes two arguments, the caller object and another object. Returns a new object that’s
the sum of the two objects
For the Point class, the add method can be like
#inside the class Point
def __add__(self, other_pt):
new_pt = Point()
new_pt.x = self.x + other_pt.x
new_pt.y = self.y + other_pt.y
return new_pt
#outside the class
>>> p1 = Point(2.0, 3.0) >>> print p1 + p2
>>> p2 = Point(3.4, 8.2) (5.4, 11.2)
Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
hour 5: oops-a-daisy special methods
the add method
__add__ is a special method like __str__ and it overloads the ’+’ operator
Takes two arguments, the caller object and another object. Returns a new object that’s
the sum of the two objects
For the Point class, the add method can be like
#inside the class Point
def __add__(self, other_pt):
new_pt = Point()
new_pt.x = self.x + other_pt.x
new_pt.y = self.y + other_pt.y
return new_pt
#outside the class
>>> p1 = Point(2.0, 3.0) >>> print p1 + p2
>>> p2 = Point(3.4, 8.2) (5.4, 11.2)
Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
another example
There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs
Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King
We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for
ranks. We’ll have trouble comparing the cards
We use integers to encode the ranks and suits
Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0
Ace → 1, Jack → 11, Queen → 12 and King → 13
Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
hour 5: oops-a-daisy an elaborate example
the class definition
class Card:
'''Represents a standard playing card'''
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'Jack', 'Queen', 'King']
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])
>>> two_of_clubs = Card() >>> queen_of_diamonds = Card(1, 12)
Satyaki Sikdar© Programming in Python April 22 2016 116 / 137
hour 5: oops-a-daisy an elaborate example
class and instance attributes
class attribute instance attribute
Defined outside any method Defined inside methods
Referred by class.class_attr Referred by inst.inst_attr
One copy per class One copy per instance
Eg: suit_names and rank_names Eg: suit and rank
Figure: Class and instance attributes
Satyaki Sikdar© Programming in Python April 22 2016 117 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
comparing cards
For built-in types, there are relational operators (<, >, ==, etc.) that compare two things
to produce a boolean
For user-defined types, we need to override the __cmp__ method. It takes in two
parameters, self and other, returns
a positive number if the first object is greater
a negative number if the second object is greater
zero if they are equal
The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of
Diamonds? One has a higher rank, but the other has a higher suit
We arbitrarily choose that suit is more important, so all the Spades outrank all the
Diamonds and so on.
Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
hour 5: oops-a-daisy an elaborate example
writing the __cmp__ method
#inside Card class
def __cmp__(self, other):
if self.suit > other.suit: #check the suits
return 1
elif self.suit < other.suit:
return -1
elif self.rank > other.rank: #check the ranks
return 1
elif self.rank < other.rank:
return -1
else: #both the suits and the ranks are the same
return 0
Satyaki Sikdar© Programming in Python April 22 2016 119 / 137
hour 5: oops-a-daisy an elaborate example
decks
Now that we have Cards, we define Decks. It will contain a list of Cards
The init method creates the entire deck of 52 cards
class Deck:
'''Represents a deck of cards'''
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
Satyaki Sikdar© Programming in Python April 22 2016 120 / 137
hour 5: oops-a-daisy an elaborate example
decks
Now that we have Cards, we define Decks. It will contain a list of Cards
The init method creates the entire deck of 52 cards
class Deck:
'''Represents a deck of cards'''
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
Satyaki Sikdar© Programming in Python April 22 2016 120 / 137
hour 5: oops-a-daisy an elaborate example
decks
#inside class Deck
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return 'n'.join(res)
def shuffle(self):
random.shuffle(self.cards)
#inside class Deck
def pop_card(self):
return self.cards.pop()
def add_card(self, card):
self.cards.append(card)
def sort(self):
self.cards.sort()
>>> deck = Deck()
>>> print deck.pop_card()
King of Spades
Satyaki Sikdar© Programming in Python April 22 2016 121 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
inheritance
The language feature most often associated with object-oriented programming is
inheritance
It’s the ability to define a new class that’s a modified version of an existing class
The existing class is called the parent and the new class is called the child
We want a class to represent a hand that is, the set of cards held by a player
A hand is similar to a deck: both are made up of a set of cards, and both require
operations like adding and removing cards
A hand is also different from a deck; there are operations we want for hands that don’t
make sense for a deck
Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
hour 5: oops-a-daisy inheritance
The definition of a child class is like other class definitions, but the name of the parent
class appears in parentheses
class Hand(Deck):
'''Represents a hand of playing cards'''
This definition indicates that Hand inherits from Deck; that means we can use methods
like pop_card and add_card for Hands as well as Decks
Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init
method for Hands should initialize cards with an empty list
We can provide an init method, overriding the one in Deck
#inside class Hand
def __init__(self, label=''):
self.cards = []
self.label = label
Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
hour 5: oops-a-daisy inheritance
The definition of a child class is like other class definitions, but the name of the parent
class appears in parentheses
class Hand(Deck):
'''Represents a hand of playing cards'''
This definition indicates that Hand inherits from Deck; that means we can use methods
like pop_card and add_card for Hands as well as Decks
Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init
method for Hands should initialize cards with an empty list
We can provide an init method, overriding the one in Deck
#inside class Hand
def __init__(self, label=''):
self.cards = []
self.label = label
Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
hour 5: oops-a-daisy inheritance
The definition of a child class is like other class definitions, but the name of the parent
class appears in parentheses
class Hand(Deck):
'''Represents a hand of playing cards'''
This definition indicates that Hand inherits from Deck; that means we can use methods
like pop_card and add_card for Hands as well as Decks
Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init
method for Hands should initialize cards with an empty list
We can provide an init method, overriding the one in Deck
#inside class Hand
def __init__(self, label=''):
self.cards = []
self.label = label
Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
hour 5: oops-a-daisy inheritance
The definition of a child class is like other class definitions, but the name of the parent
class appears in parentheses
class Hand(Deck):
'''Represents a hand of playing cards'''
This definition indicates that Hand inherits from Deck; that means we can use methods
like pop_card and add_card for Hands as well as Decks
Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init
method for Hands should initialize cards with an empty list
We can provide an init method, overriding the one in Deck
#inside class Hand
def __init__(self, label=''):
self.cards = []
self.label = label
Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
hour 5: oops-a-daisy inheritance
So when you create a Hand,
Python invokes it’s own init
>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand
But the other methods are inherited from Deck
>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card) #add_card from Hand
>>> print hand #using the str of Hand
King of Spades
A natural next step is to encapsulate this code in a method called move_cards
#inside class Deck
def move_cards(self, hand, card):
for i in xrange(num):
hand.add_card(self.pop_card())
move_cards takes two arguments, a Hand object and the number of cards to deal.
Modifies both self and hand
Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
hour 5: oops-a-daisy inheritance
So when you create a Hand,
Python invokes it’s own init
>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand
But the other methods are inherited from Deck
>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card) #add_card from Hand
>>> print hand #using the str of Hand
King of Spades
A natural next step is to encapsulate this code in a method called move_cards
#inside class Deck
def move_cards(self, hand, card):
for i in xrange(num):
hand.add_card(self.pop_card())
move_cards takes two arguments, a Hand object and the number of cards to deal.
Modifies both self and hand
Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
hour 5: oops-a-daisy inheritance
So when you create a Hand,
Python invokes it’s own init
>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand
But the other methods are inherited from Deck
>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card) #add_card from Hand
>>> print hand #using the str of Hand
King of Spades
A natural next step is to encapsulate this code in a method called move_cards
#inside class Deck
def move_cards(self, hand, card):
for i in xrange(num):
hand.add_card(self.pop_card())
move_cards takes two arguments, a Hand object and the number of cards to deal.
Modifies both self and hand
Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
hour 5: oops-a-daisy inheritance
So when you create a Hand,
Python invokes it’s own init
>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand
But the other methods are inherited from Deck
>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card) #add_card from Hand
>>> print hand #using the str of Hand
King of Spades
A natural next step is to encapsulate this code in a method called move_cards
#inside class Deck
def move_cards(self, hand, card):
for i in xrange(num):
hand.add_card(self.pop_card())
move_cards takes two arguments, a Hand object and the number of cards to deal.
Modifies both self and hand
Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
hour 5: oops-a-daisy inheritance
#inside class Deck
def deal_hands(self, num_hands, cards_per_hand):
hands = []
self.shuffle() #shuffling the deck
for i in range(num_hands):
hand = Hand('player %d' % (i))
for j in range(cards_per_hand):
hand.add_card(self.pop_card())
hands.append(hand)
return hands
Now you have a proper framework for a card game, be it poker, blackjack or bridge!
Satyaki Sikdar© Programming in Python April 22 2016 125 / 137
hour 5: oops-a-daisy file handling 101
the need for file handling
Most of the programs we have seen so far are transient in the sense that they run for a
short time and produce some output, but when they end, their data disappears. If you run
the program again, it starts with a clean slate
Other programs are persistent: they run for a long time (or all the time); they keep at
least some of their data in permanent storage (a hard drive, for example); if they shut
down and restart, they pick up where they left off
Big input and output sizes - too big for the main memory
Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
hour 5: oops-a-daisy file handling 101
the need for file handling
Most of the programs we have seen so far are transient in the sense that they run for a
short time and produce some output, but when they end, their data disappears. If you run
the program again, it starts with a clean slate
Other programs are persistent: they run for a long time (or all the time); they keep at
least some of their data in permanent storage (a hard drive, for example); if they shut
down and restart, they pick up where they left off
Big input and output sizes - too big for the main memory
Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
hour 5: oops-a-daisy file handling 101
the need for file handling
Most of the programs we have seen so far are transient in the sense that they run for a
short time and produce some output, but when they end, their data disappears. If you run
the program again, it starts with a clean slate
Other programs are persistent: they run for a long time (or all the time); they keep at
least some of their data in permanent storage (a hard drive, for example); if they shut
down and restart, they pick up where they left off
Big input and output sizes - too big for the main memory
Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
hour 5: oops-a-daisy file handling 101
Examples of persistent programs are operating systems, which run pretty much whenever a
computer is on, and web servers, which run all the time, waiting for requests to come in on
the network.
One of the simplest ways for programs to maintain their data is by reading and writing
text files.
fp_read = open('input.txt', 'r')
fp_write = open('output.txt', 'w')
Satyaki Sikdar© Programming in Python April 22 2016 127 / 137
hour 5: oops-a-daisy file handling 101
Examples of persistent programs are operating systems, which run pretty much whenever a
computer is on, and web servers, which run all the time, waiting for requests to come in on
the network.
One of the simplest ways for programs to maintain their data is by reading and writing
text files.
fp_read = open('input.txt', 'r')
fp_write = open('output.txt', 'w')
Satyaki Sikdar© Programming in Python April 22 2016 127 / 137
hour 5: oops-a-daisy file handling 101
reading from files
The built-in function open takes the name of the file as a parameter and returns a file
object you can use to read the file
>>> fin = open('input.txt', 'r')
>>> print fin
>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>
A few things to note: The file opened must exist. An IOError is thrown otherwise.
The exact path to the file must be provided which includes the correct filename with
extension (if any)
Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
hour 5: oops-a-daisy file handling 101
reading from files
The built-in function open takes the name of the file as a parameter and returns a file
object you can use to read the file
>>> fin = open('input.txt', 'r')
>>> print fin
>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>
A few things to note: The file opened must exist. An IOError is thrown otherwise.
The exact path to the file must be provided which includes the correct filename with
extension (if any)
Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
hour 5: oops-a-daisy file handling 101
reading from files
The built-in function open takes the name of the file as a parameter and returns a file
object you can use to read the file
>>> fin = open('input.txt', 'r')
>>> print fin
>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>
A few things to note: The file opened must exist. An IOError is thrown otherwise.
The exact path to the file must be provided which includes the correct filename with
extension (if any)
Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
hour 5: oops-a-daisy file handling 101
reading from files
The built-in function open takes the name of the file as a parameter and returns a file
object you can use to read the file
>>> fin = open('input.txt', 'r')
>>> print fin
>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>
A few things to note: The file opened must exist. An IOError is thrown otherwise.
The exact path to the file must be provided which includes the correct filename with
extension (if any)
Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
hour 5: oops-a-daisy file handling 101
reading files
The file object provides several methods for reading, including readline, which reads
characters from the file until it gets to a newline and returns the result as a string:
>>> fin.readline()
'the first line n'
If you keep on doing fin.readlines(), you’d end up reading the whole file, one line at a time.
Let’s see a few examples of reading files.
Satyaki Sikdar© Programming in Python April 22 2016 129 / 137
hour 5: oops-a-daisy file handling 101
writing to files
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
If the file already exists, opening it in write mode clears out the old data and starts fresh,
so be careful! If the file doesn’t exist, a new one is created
>>> line1 = 'He left yesterday behind him, you might say he was born again,
>>> fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds the new
data to the end
>>> line2 = 'you might say he found a key for every door.n'
>>> fout.write(line2)
Satyaki Sikdar© Programming in Python April 22 2016 130 / 137
hour 5: oops-a-daisy file handling 101
using files for something meaningful
Let’s combine the knowledge of file handling with dictionaries to do some basic lexical analysis
import string
def char_freq(filename):
counter = dict()
with open(filename, 'r') as f:
raw_text = f.read()
for c in raw_text:
c = c.lower()
if c in string.ascii_lowercase:
if c in counter:
counter[c] += 1
else:
counter[c] = 1
return counter
def normalize(counter):
sum_values = float(sum(counter.values()))
for key in counter:
counter[key] /= sum_values
return counter
Satyaki Sikdar© Programming in Python April 22 2016 131 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy algorithms in Python
algorithm design in Python
One of the strong points of Python is the ease of expression
Turning pseudocode into actual code is not difficult
Let’s try to implement the Merge Sort algorithm in Python
A high level idea of the algorithm
Divide: Divide the n-element sequence into two subsequences of n
2 elements
Conquer: Sort the subsequences recursively
Combine: Merge the two sorted subsequences to produce the sorted answer
Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
hour 5: oops-a-daisy the pseudocode
Algorithm 1: MERGE(left, right)
begin
Append ∞ to left and right
i ← 0, j ← 0
merged ← new list
while len(merged) < len(left) + len(right) do
if left[i] < right[j] then
merged.append(left[i])
i ← i + 1
else
merged.append(right[j])
j ← j + 1
return merged
Algorithm 2: MERGE-SORT(A)
begin
if len(A) < 2 then
return A
else
left ← first n
2 elements of A
right ← last n
2 elements of A
left ← MERGE − SORT(left)
right ←
MERGE − SORT(right)
return MERGE(left, right)
Satyaki Sikdar© Programming in Python April 22 2016 133 / 137
hour 5: oops-a-daisy the pseudocode
the core idea
The algorithm is naturally recursive
The MERGE method takes two sorted lists and merges into a single sorted list
MERGE − SORT sorts the list recursively by breaking it into equal sized halves and
sorting them
A list having less than 2 elements is trivially sorted - base case
Smaller sorted lists are agglomerated to form the overall sorted list
Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
hour 5: oops-a-daisy the pseudocode
the core idea
The algorithm is naturally recursive
The MERGE method takes two sorted lists and merges into a single sorted list
MERGE − SORT sorts the list recursively by breaking it into equal sized halves and
sorting them
A list having less than 2 elements is trivially sorted - base case
Smaller sorted lists are agglomerated to form the overall sorted list
Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
hour 5: oops-a-daisy the pseudocode
the core idea
The algorithm is naturally recursive
The MERGE method takes two sorted lists and merges into a single sorted list
MERGE − SORT sorts the list recursively by breaking it into equal sized halves and
sorting them
A list having less than 2 elements is trivially sorted - base case
Smaller sorted lists are agglomerated to form the overall sorted list
Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
hour 5: oops-a-daisy the pseudocode
the core idea
The algorithm is naturally recursive
The MERGE method takes two sorted lists and merges into a single sorted list
MERGE − SORT sorts the list recursively by breaking it into equal sized halves and
sorting them
A list having less than 2 elements is trivially sorted - base case
Smaller sorted lists are agglomerated to form the overall sorted list
Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
hour 5: oops-a-daisy the pseudocode
the core idea
The algorithm is naturally recursive
The MERGE method takes two sorted lists and merges into a single sorted list
MERGE − SORT sorts the list recursively by breaking it into equal sized halves and
sorting them
A list having less than 2 elements is trivially sorted - base case
Smaller sorted lists are agglomerated to form the overall sorted list
Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
hour 5: oops-a-daisy implementation
Algorithm 3: MERGE(left, right)
begin
Append ∞ to left and right
i ← 0, j ← 0
merged ← new list
while len(merged) < len(left) + len(right) do
if left[i] < right[j] then
merged.append(left[i])
i ← i + 1
else
merged.append(right[j])
j ← j + 1
return merged
def merge(left, right):
left.append(float('inf'))
right.append(float('inf'))
i = 0
j = 0
merged = []
while len(merged) < len(left) +
len(right):
if left[i] < right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
return merged
Satyaki Sikdar© Programming in Python April 22 2016 135 / 137
hour 5: oops-a-daisy implementation
Algorithm 4: MERGE-SORT(A)
begin
if len(A) < 2 then
return A
else
left ← first n
2 elements of A
right ← last n
2 elements of A
left ← MERGE − SORT(left)
right ← MERGE − SORT(right)
return MERGE(left, right)
def merge_sort(A):
if len(A) < 2:
return A
else:
mid = len(A) / 2
left = A[: mid]
right = A[mid: ]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
Satyaki Sikdar© Programming in Python April 22 2016 136 / 137
hour 5: oops-a-daisy implementation
That’s all for today! Hope you had fun! Make sure you have a working
networkx setup for tomorrow...
Satyaki Sikdar© Programming in Python April 22 2016 137 / 137

More Related Content

PDF
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
PDF
Learn python in one day and learn it well python for beginners with hands on...
PDF
Learn python in one day and learn it well the only book you need to start c...
PDF
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
PDF
Workshop on Programming in Python - day II
PDF
Learn 90% of Python in 90 Minutes
PDF
An Introduction to Python Programming
PPTX
Intro to Python Programming Language
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...
Learn python in one day and learn it well python for beginners with hands on...
Learn python in one day and learn it well the only book you need to start c...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Workshop on Programming in Python - day II
Learn 90% of Python in 90 Minutes
An Introduction to Python Programming
Intro to Python Programming Language

Viewers also liked (20)

PPT
Introduction to Python
KEY
Corso Python Deltapromo - Lezione 5
KEY
Corso Python Deltapromo - Lezione 4
PDF
Reportlab Corso Python avanzato - ForDataScientist 01
PDF
Matplotlib: Corso Python avanzato - ForDataScientist 01
PDF
Python 101
PDF
Python in-the-enterprise-brochure
PDF
Python Programming - I. Introduction
PDF
Using hadoop for big data
PDF
Meetup Python Nantes - les tests en python
PPTX
Introduction to Advanced Javascript
PDF
Python - Lecture 1
PDF
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
PDF
Learning notes of r for python programmer (Temp1)
PDF
Java OOP Programming language (Part 1) - Introduction to Java
PPT
Operator Overloading
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
PDF
Python Programming - V. Sequences (List and Tuples) and Dictionaries
PDF
Python for All
PDF
Installing Python on Mac
Introduction to Python
Corso Python Deltapromo - Lezione 5
Corso Python Deltapromo - Lezione 4
Reportlab Corso Python avanzato - ForDataScientist 01
Matplotlib: Corso Python avanzato - ForDataScientist 01
Python 101
Python in-the-enterprise-brochure
Python Programming - I. Introduction
Using hadoop for big data
Meetup Python Nantes - les tests en python
Introduction to Advanced Javascript
Python - Lecture 1
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Learning notes of r for python programmer (Temp1)
Java OOP Programming language (Part 1) - Introduction to Java
Operator Overloading
PyCon 2013 : Scripting to PyPi to GitHub and More
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Python for All
Installing Python on Mac
Ad

Similar to A 12 hour workshop on Introduction to Python (20)

PPTX
Introduction to Python - Code Heroku
PPTX
Introduction-Learning-Python-Quickly.pptx
DOCX
python training.docx
PDF
Master Python.pdf
PDF
Master Python.pdf
PPTX
Step by step python(week1)
PDF
Python Courses in Chandigarh.........pdf
PPTX
EdTechJoker Spring 2020 - Lecture 1 - Welcome
PDF
Why should I learn python
PPTX
Career in python
PDF
Become a Python Pro at Zoople Technologies, Koch
DOC
1 cover page
PDF
Python developer roles, responsibilities, and salaries in 2023
PDF
PYTHON PROGRAMMING FOR HACKERS. PART 1 – GETTING STARTED
PDF
Python pandas tutorial
PPTX
Hactoberfest presentation
PDF
Python in Action.pdf
PDF
Datascope runs on python
PDF
Growing with the Open-Source Community
PDF
interviewbit.pdf
Introduction to Python - Code Heroku
Introduction-Learning-Python-Quickly.pptx
python training.docx
Master Python.pdf
Master Python.pdf
Step by step python(week1)
Python Courses in Chandigarh.........pdf
EdTechJoker Spring 2020 - Lecture 1 - Welcome
Why should I learn python
Career in python
Become a Python Pro at Zoople Technologies, Koch
1 cover page
Python developer roles, responsibilities, and salaries in 2023
PYTHON PROGRAMMING FOR HACKERS. PART 1 – GETTING STARTED
Python pandas tutorial
Hactoberfest presentation
Python in Action.pdf
Datascope runs on python
Growing with the Open-Source Community
interviewbit.pdf
Ad

Recently uploaded (20)

PPTX
Education and Perspectives of Education.pptx
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
PDF
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
HVAC Specification 2024 according to central public works department
PPTX
Computer Architecture Input Output Memory.pptx
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
Education and Perspectives of Education.pptx
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Share_Module_2_Power_conflict_and_negotiation.pptx
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
What if we spent less time fighting change, and more time building what’s rig...
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
HVAC Specification 2024 according to central public works department
Computer Architecture Input Output Memory.pptx
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
FORM 1 BIOLOGY MIND MAPS and their schemes

A 12 hour workshop on Introduction to Python

  • 1. Programming in Python A Two Day Workshop Satyaki Sikdar Vice Chair ACM Student Chapter Heritage Institute of Technology April 22 2016 Satyaki Sikdar© Programming in Python April 22 2016 1 / 137
  • 2. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 3. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 4. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 5. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 6. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 7. hour 0: intro whoami whoami Extremely lazy Coding in Python since the summer of 2013 - not an expert by any means An average programmer at best. Comfortable writing 750 - 1000 lines of code In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro and professional I love Python - duh! Working in SNA for the past 15 months under the supervision of Prof. Dr. Partha Basuchowdhuri and Prof. Dr. Subhashis Majumder. Learning Python paid off big time! Satyaki Sikdar© Programming in Python April 22 2016 2 / 137
  • 8. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 9. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 10. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 11. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 12. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 13. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 14. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 15. hour 0: intro expectations and takeaways great expectations Things you can expect from me Clarity No spoon feeding Desperate attempts at making jokes Things I expect from you An open mind Patience - not everything would make perfect sense at first Attention - especially to details Cooperation - it’s going to be a long haul Interruptions - feel free to stop me to ask relevant questions Satyaki Sikdar© Programming in Python April 22 2016 3 / 137
  • 16. hour 0: intro expectations and takeaways your takeaways 1 A degree of fluency in reading and writing short - medium Python codes 2 A knowledge of how things work in Python and why certain things are done in a certain way 3 Learning something exciting - might not be only Python 4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
  • 17. hour 0: intro expectations and takeaways your takeaways 1 A degree of fluency in reading and writing short - medium Python codes 2 A knowledge of how things work in Python and why certain things are done in a certain way 3 Learning something exciting - might not be only Python 4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
  • 18. hour 0: intro expectations and takeaways your takeaways 1 A degree of fluency in reading and writing short - medium Python codes 2 A knowledge of how things work in Python and why certain things are done in a certain way 3 Learning something exciting - might not be only Python 4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
  • 19. hour 0: intro expectations and takeaways your takeaways 1 A degree of fluency in reading and writing short - medium Python codes 2 A knowledge of how things work in Python and why certain things are done in a certain way 3 Learning something exciting - might not be only Python 4 A formal but very brief introduction Social Network Analysis, a vibrant field of CS Satyaki Sikdar© Programming in Python April 22 2016 4 / 137
  • 20. hour 0: intro lesson plan the lesson plan for day I hour topic 1 introduction, motivation, Guido, awesomeness of Python 2 playing around with the interpreter - variables, simple data types 3 predefined functions, conditionals, lists, loops 4 tuples, user defined functions, basic recursion 5 sets, dictionaries, errors and exceptions, intro to OOP 6 OOP - inheritance, applying OOP Satyaki Sikdar© Programming in Python April 22 2016 5 / 137
  • 21. hour 0: intro Guido Maester Guido van Rossum The Dutch are known for their easygoing nature. And Guido is no different. Figure: Guido van Rossum Born: 31 January, 1956 in Haarlem, The Netherlands Studied Computer Science from the University of Amsterdam Started Python as a hobby project in 1989. It grew into a new language in a couple of years. Recognized as a Distinguished Engineer by ACM Xoogler and now works for Dropbox Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
  • 22. hour 0: intro Guido Maester Guido van Rossum The Dutch are known for their easygoing nature. And Guido is no different. Figure: Guido van Rossum Born: 31 January, 1956 in Haarlem, The Netherlands Studied Computer Science from the University of Amsterdam Started Python as a hobby project in 1989. It grew into a new language in a couple of years. Recognized as a Distinguished Engineer by ACM Xoogler and now works for Dropbox Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
  • 23. hour 0: intro Guido Maester Guido van Rossum The Dutch are known for their easygoing nature. And Guido is no different. Figure: Guido van Rossum Born: 31 January, 1956 in Haarlem, The Netherlands Studied Computer Science from the University of Amsterdam Started Python as a hobby project in 1989. It grew into a new language in a couple of years. Recognized as a Distinguished Engineer by ACM Xoogler and now works for Dropbox Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
  • 24. hour 0: intro Guido Maester Guido van Rossum The Dutch are known for their easygoing nature. And Guido is no different. Figure: Guido van Rossum Born: 31 January, 1956 in Haarlem, The Netherlands Studied Computer Science from the University of Amsterdam Started Python as a hobby project in 1989. It grew into a new language in a couple of years. Recognized as a Distinguished Engineer by ACM Xoogler and now works for Dropbox Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
  • 25. hour 0: intro Guido Maester Guido van Rossum The Dutch are known for their easygoing nature. And Guido is no different. Figure: Guido van Rossum Born: 31 January, 1956 in Haarlem, The Netherlands Studied Computer Science from the University of Amsterdam Started Python as a hobby project in 1989. It grew into a new language in a couple of years. Recognized as a Distinguished Engineer by ACM Xoogler and now works for Dropbox Satyaki Sikdar© Programming in Python April 22 2016 6 / 137
  • 26. hour 0: intro popularity it’s good to be popular It’s true for people and programming languages alike Tons of resources to get help from if you are stuck You’ll get a lot of people to collaborate Employment opportunities open up Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
  • 27. hour 0: intro popularity it’s good to be popular It’s true for people and programming languages alike Tons of resources to get help from if you are stuck You’ll get a lot of people to collaborate Employment opportunities open up Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
  • 28. hour 0: intro popularity it’s good to be popular It’s true for people and programming languages alike Tons of resources to get help from if you are stuck You’ll get a lot of people to collaborate Employment opportunities open up Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
  • 29. hour 0: intro popularity it’s good to be popular It’s true for people and programming languages alike Tons of resources to get help from if you are stuck You’ll get a lot of people to collaborate Employment opportunities open up Satyaki Sikdar© Programming in Python April 22 2016 7 / 137
  • 30. hour 0: intro popularity popularity of Python ©codeeval - hiring demand trends Satyaki Sikdar© Programming in Python April 22 2016 8 / 137
  • 31. hour 0: intro popularity popularity of Python ©PYPL Satyaki Sikdar© Programming in Python April 22 2016 9 / 137
  • 32. hour 0: intro popularity popularity of Python Satyaki Sikdar© Programming in Python April 22 2016 10 / 137
  • 33. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 34. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 35. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 36. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 37. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 38. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 39. hour 0: intro awesomeness of Python what makes Py Awesome? Open source license - right from the early days Very versatile The Zen of Python - you should read it every now and then A strong and active community PyPI - the modules repository has over 30, 000 user created modules for ready use Killer apps like Django and Pandas Lots and lots of reference materials available including books, video lectures and tutorials Satyaki Sikdar© Programming in Python April 22 2016 11 / 137
  • 40. hour 0: intro awesomeness of Python the awesomeness continues! Ease of learning - you’ll see it soon Very teachable - low syntax overhead Rapid development cycle - easy to express yourself Readable, beautiful and brevity - you’ll love to code Interactive prompt Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
  • 41. hour 0: intro awesomeness of Python the awesomeness continues! Ease of learning - you’ll see it soon Very teachable - low syntax overhead Rapid development cycle - easy to express yourself Readable, beautiful and brevity - you’ll love to code Interactive prompt Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
  • 42. hour 0: intro awesomeness of Python the awesomeness continues! Ease of learning - you’ll see it soon Very teachable - low syntax overhead Rapid development cycle - easy to express yourself Readable, beautiful and brevity - you’ll love to code Interactive prompt Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
  • 43. hour 0: intro awesomeness of Python the awesomeness continues! Ease of learning - you’ll see it soon Very teachable - low syntax overhead Rapid development cycle - easy to express yourself Readable, beautiful and brevity - you’ll love to code Interactive prompt Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
  • 44. hour 0: intro awesomeness of Python the awesomeness continues! Ease of learning - you’ll see it soon Very teachable - low syntax overhead Rapid development cycle - easy to express yourself Readable, beautiful and brevity - you’ll love to code Interactive prompt Satyaki Sikdar© Programming in Python April 22 2016 12 / 137
  • 45. hour 0: intro awesomeness of Python ©xkcd.com Satyaki Sikdar© Programming in Python April 22 2016 13 / 137
  • 46. hour 0: intro awesomeness of Python places were Py is used From supercomputers to Instagram, from labs to financial firms You can do machine learning, NLP to building web pages and wrangling social networks Really hip among startups Schools like M.I.T., Rice, Stanford, Havard have switched to Python for their programming courses in the CS curriculum Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
  • 47. hour 0: intro awesomeness of Python places were Py is used From supercomputers to Instagram, from labs to financial firms You can do machine learning, NLP to building web pages and wrangling social networks Really hip among startups Schools like M.I.T., Rice, Stanford, Havard have switched to Python for their programming courses in the CS curriculum Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
  • 48. hour 0: intro awesomeness of Python places were Py is used From supercomputers to Instagram, from labs to financial firms You can do machine learning, NLP to building web pages and wrangling social networks Really hip among startups Schools like M.I.T., Rice, Stanford, Havard have switched to Python for their programming courses in the CS curriculum Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
  • 49. hour 0: intro awesomeness of Python places were Py is used From supercomputers to Instagram, from labs to financial firms You can do machine learning, NLP to building web pages and wrangling social networks Really hip among startups Schools like M.I.T., Rice, Stanford, Havard have switched to Python for their programming courses in the CS curriculum Satyaki Sikdar© Programming in Python April 22 2016 14 / 137
  • 50. hour 0: intro indentation indentation continues Pseudocode on the left and Python code on the right Figure: From CLRS def INSERTION_SORT(A): for j in xrange(1, len(A)): key = A[j] i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i -= 1 A[i + 1] = key Satyaki Sikdar© Programming in Python April 22 2016 15 / 137
  • 51. hour 0: intro indentation indentation & Python It’s absolutely essential to indent Python code. It seems natural Braces? Yuck!! According to PEP8, you must indent every block of code by 4 spaces Mess up the indentation, and your precious code becomes garbage from __future__ import braces # File "<stdin>", line 1 # SyntaxError: not a chance Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
  • 52. hour 0: intro indentation indentation & Python It’s absolutely essential to indent Python code. It seems natural Braces? Yuck!! According to PEP8, you must indent every block of code by 4 spaces Mess up the indentation, and your precious code becomes garbage from __future__ import braces # File "<stdin>", line 1 # SyntaxError: not a chance Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
  • 53. hour 0: intro indentation indentation & Python It’s absolutely essential to indent Python code. It seems natural Braces? Yuck!! According to PEP8, you must indent every block of code by 4 spaces Mess up the indentation, and your precious code becomes garbage from __future__ import braces # File "<stdin>", line 1 # SyntaxError: not a chance Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
  • 54. hour 0: intro indentation indentation & Python It’s absolutely essential to indent Python code. It seems natural Braces? Yuck!! According to PEP8, you must indent every block of code by 4 spaces Mess up the indentation, and your precious code becomes garbage from __future__ import braces # File "<stdin>", line 1 # SyntaxError: not a chance Satyaki Sikdar© Programming in Python April 22 2016 16 / 137
  • 55. hour 1: Python 101 the interpreter and more .. say hello to the interpreter! Python is an interpreted language. It executes codes line by line It has an interactive prompt with which you can play around without any fear The prompt looks like this >>> You can do everything you want in this interpreter. We’ll play around with it now. Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
  • 56. hour 1: Python 101 the interpreter and more .. say hello to the interpreter! Python is an interpreted language. It executes codes line by line It has an interactive prompt with which you can play around without any fear The prompt looks like this >>> You can do everything you want in this interpreter. We’ll play around with it now. Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
  • 57. hour 1: Python 101 the interpreter and more .. say hello to the interpreter! Python is an interpreted language. It executes codes line by line It has an interactive prompt with which you can play around without any fear The prompt looks like this >>> You can do everything you want in this interpreter. We’ll play around with it now. Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
  • 58. hour 1: Python 101 the interpreter and more .. say hello to the interpreter! Python is an interpreted language. It executes codes line by line It has an interactive prompt with which you can play around without any fear The prompt looks like this >>> You can do everything you want in this interpreter. We’ll play around with it now. Satyaki Sikdar© Programming in Python April 22 2016 17 / 137
  • 59. hour 1: Python 101 the interpreter and more .. the print statement It’s one of the most used statements in Python Does what the name says, it prints stuff It’s very smart - one statement to rule them all - works for every data type - no messy loops needed print 1 + 1 # >>> 2 print 'joe root' # >>> joe root (notice the lack of quotes) print True # >>> True print 'hello', 'world' # >>> hello world (notice the space) print 'hello' print 'world' #hello and world in separate lines print 'hello', print 'world' #hello and world in the same line (notice the comma) Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
  • 60. hour 1: Python 101 the interpreter and more .. the print statement It’s one of the most used statements in Python Does what the name says, it prints stuff It’s very smart - one statement to rule them all - works for every data type - no messy loops needed print 1 + 1 # >>> 2 print 'joe root' # >>> joe root (notice the lack of quotes) print True # >>> True print 'hello', 'world' # >>> hello world (notice the space) print 'hello' print 'world' #hello and world in separate lines print 'hello', print 'world' #hello and world in the same line (notice the comma) Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
  • 61. hour 1: Python 101 the interpreter and more .. the print statement It’s one of the most used statements in Python Does what the name says, it prints stuff It’s very smart - one statement to rule them all - works for every data type - no messy loops needed print 1 + 1 # >>> 2 print 'joe root' # >>> joe root (notice the lack of quotes) print True # >>> True print 'hello', 'world' # >>> hello world (notice the space) print 'hello' print 'world' #hello and world in separate lines print 'hello', print 'world' #hello and world in the same line (notice the comma) Satyaki Sikdar© Programming in Python April 22 2016 18 / 137
  • 62. hour 1: Python 101 the interpreter and more .. the print statement formatter = '%s %s %s %s' print formatter % (1, 2, 3, 4) print formatter % ('one', 'two', 'three', 'four') print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, formatter) print formatter % ('I had this thing.', 'That you could type up right.', "But it didn't sing.", 'So I said goodnight.') Satyaki Sikdar© Programming in Python April 22 2016 19 / 137
  • 63. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 64. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 65. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 66. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 67. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 68. hour 1: Python 101 data types data types in Python There are 6 basic data types in Python 1 integers (int), eg: 1, 23, 1245322 2 long integers (long). These usually end with a L at the end, eg: 1071645932315929337037L 3 floating point numbers (float): Has a decimal point somewhere. Eg: 1.2, 42.0. Even 4. is a valid floating point number. 4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complex number in Python. 5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both valid strings, but ’jimmy anderson" or "jimmy anderson’ is not. 6 booleans (bool): True and False Satyaki Sikdar© Programming in Python April 22 2016 20 / 137
  • 69. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 70. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 71. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 72. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 73. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 74. hour 1: Python 101 integers integers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50 + 7 gives 57 * for multiplication. Eg: 50 * 7 gives 350 / for integer division. Eg: 50 / 7 gives 7 (why?) % for modulo operation. Eg: 50 % 7 gives 1 ** for exponentiation. Eg: 2 ** 7 gives 128 >>, <<, ˜ are also allowed Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 21 / 137
  • 75. hour 1: Python 101 floats floating point numbers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50.2 + 7.4 gives 57.6 * for multiplication. Eg: 50.2 * 5 gives 251.0 / for division. Eg: 50.0 / 7 gives 7.1428 % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999 ** for exponentiation. Eg: 2.2 ** 7 gives 249.43578 Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
  • 76. hour 1: Python 101 floats floating point numbers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50.2 + 7.4 gives 57.6 * for multiplication. Eg: 50.2 * 5 gives 251.0 / for division. Eg: 50.0 / 7 gives 7.1428 % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999 ** for exponentiation. Eg: 2.2 ** 7 gives 249.43578 Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
  • 77. hour 1: Python 101 floats floating point numbers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50.2 + 7.4 gives 57.6 * for multiplication. Eg: 50.2 * 5 gives 251.0 / for division. Eg: 50.0 / 7 gives 7.1428 % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999 ** for exponentiation. Eg: 2.2 ** 7 gives 249.43578 Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
  • 78. hour 1: Python 101 floats floating point numbers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50.2 + 7.4 gives 57.6 * for multiplication. Eg: 50.2 * 5 gives 251.0 / for division. Eg: 50.0 / 7 gives 7.1428 % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999 ** for exponentiation. Eg: 2.2 ** 7 gives 249.43578 Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
  • 79. hour 1: Python 101 floats floating point numbers Supports basic operations as it is expected to. Any of the things shouldn’t come as a surprise to you. + for addition. Eg: 50.2 + 7.4 gives 57.6 * for multiplication. Eg: 50.2 * 5 gives 251.0 / for division. Eg: 50.0 / 7 gives 7.1428 % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999 ** for exponentiation. Eg: 2.2 ** 7 gives 249.43578 Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 22 / 137
  • 80. hour 1: Python 101 complex numbers complex numbers Note: j is used in place of i + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j) * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j) / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j) % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j) ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
  • 81. hour 1: Python 101 complex numbers complex numbers Note: j is used in place of i + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j) * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j) / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j) % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j) ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
  • 82. hour 1: Python 101 complex numbers complex numbers Note: j is used in place of i + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j) * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j) / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j) % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j) ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
  • 83. hour 1: Python 101 complex numbers complex numbers Note: j is used in place of i + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j) * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j) / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j) % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j) ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
  • 84. hour 1: Python 101 complex numbers complex numbers Note: j is used in place of i + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j) * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j) / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j) % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j) ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40j Parenthization of expressions is allowed with the help of () Satyaki Sikdar© Programming in Python April 22 2016 23 / 137
  • 85. hour 1: Python 101 strings no strings attached! Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH Bigger strings consist of smaller strings. There’s no such thing as a character in Python. + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’ and ’Cook’ + ’Alastair’ gives ’CookAlastair’ * used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’ Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
  • 86. hour 1: Python 101 strings no strings attached! Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH Bigger strings consist of smaller strings. There’s no such thing as a character in Python. + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’ and ’Cook’ + ’Alastair’ gives ’CookAlastair’ * used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’ Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
  • 87. hour 1: Python 101 strings no strings attached! Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH Bigger strings consist of smaller strings. There’s no such thing as a character in Python. + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’ and ’Cook’ + ’Alastair’ gives ’CookAlastair’ * used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’ Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
  • 88. hour 1: Python 101 strings no strings attached! Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH Bigger strings consist of smaller strings. There’s no such thing as a character in Python. + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’ and ’Cook’ + ’Alastair’ gives ’CookAlastair’ * used to append the same string to itself. Eg: ’yay ’ * 3 gives ’yay yay yay’ Satyaki Sikdar© Programming in Python April 22 2016 24 / 137
  • 89. hour 1: Python 101 strings string methods - I Here’s a subset of the many in-built functions and methods that can be used with strings. len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6 indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1] => ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so on. slicing: Returns a part of the string. So string[start: end] slices the string from index = start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2: 6] => ’hate’ Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
  • 90. hour 1: Python 101 strings string methods - I Here’s a subset of the many in-built functions and methods that can be used with strings. len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6 indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1] => ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so on. slicing: Returns a part of the string. So string[start: end] slices the string from index = start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2: 6] => ’hate’ Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
  • 91. hour 1: Python 101 strings string methods - I Here’s a subset of the many in-built functions and methods that can be used with strings. len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6 indexing :- Starts from 0. So, ’batman’[0] => ’b’, .., up to ’batman’[len(’batman’) - 1] => ’n’ . Negative indexing is also valid! ’batman’[-1] => ’n’, ’batman’[-2] => ’a’ and so on. slicing: Returns a part of the string. So string[start: end] slices the string from index = start, goes all the way to end - 1 and returns the new string. Eg: ’I hate Shane Warne’[2: 6] => ’hate’ Satyaki Sikdar© Programming in Python April 22 2016 25 / 137
  • 92. hour 1: Python 101 strings string methods - II s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home for imaginary friends’ .count (’fo’) = 2 s.find(substring) :- gives you the index of the substring in the string. Eg: ’Alastair’.find(’stair’) = 3 s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ] If delim is omitted, whitespace is used by default Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
  • 93. hour 1: Python 101 strings string methods - II s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home for imaginary friends’ .count (’fo’) = 2 s.find(substring) :- gives you the index of the substring in the string. Eg: ’Alastair’.find(’stair’) = 3 s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ] If delim is omitted, whitespace is used by default Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
  • 94. hour 1: Python 101 strings string methods - II s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s home for imaginary friends’ .count (’fo’) = 2 s.find(substring) :- gives you the index of the substring in the string. Eg: ’Alastair’.find(’stair’) = 3 s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’Alastair Cook is the best’.split(’ ’) returns [ Alastair , Cook , is , the , best ] If delim is omitted, whitespace is used by default Satyaki Sikdar© Programming in Python April 22 2016 26 / 137
  • 95. hour 1: Python 101 strings string slicing - revisited So far, we have sliced strings in a manner like st[start: end] You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaults to 1. But what does that mean? Let’s find out! st = '0123456789' for c in st[: : 1]: print c, #output: 0 1 2 3 4 5 6 7 8 9 for c in st[: : 2]: print c, #output: 0 2 4 6 8 for c in st[: : 3]: print c, #output: 0 3 6 9 for c in st[: : -1]: print c, #output: 9 8 7 6 5 4 3 2 1 0 WHOA! Really?! # what about st[: : -2]? Find it out! Satyaki Sikdar© Programming in Python April 22 2016 27 / 137
  • 96. hour 1: Python 101 strings string slicing - revisited So far, we have sliced strings in a manner like st[start: end] You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaults to 1. But what does that mean? Let’s find out! st = '0123456789' for c in st[: : 1]: print c, #output: 0 1 2 3 4 5 6 7 8 9 for c in st[: : 2]: print c, #output: 0 2 4 6 8 for c in st[: : 3]: print c, #output: 0 3 6 9 for c in st[: : -1]: print c, #output: 9 8 7 6 5 4 3 2 1 0 WHOA! Really?! # what about st[: : -2]? Find it out! Satyaki Sikdar© Programming in Python April 22 2016 27 / 137
  • 97. hour 1: Python 101 strings palindrome checking A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal, Panama!’ Often it’s allowed to skip over spaces and punctuation marks It’s a classic problem while dealing with strings. And we’ll stick to character-unit palindromes. Example: redivider, noon, radar, madam, refer, etc. We’ll see a simple one liner code that checks if a string is a palindrome. >>> st = 'refer' >>> if st == st[: : -1]: # st == st.reverse() does the same thing print st, 'is a palindrome' else: print st, 'is not a palindrome' Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
  • 98. hour 1: Python 101 strings palindrome checking A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal, Panama!’ Often it’s allowed to skip over spaces and punctuation marks It’s a classic problem while dealing with strings. And we’ll stick to character-unit palindromes. Example: redivider, noon, radar, madam, refer, etc. We’ll see a simple one liner code that checks if a string is a palindrome. >>> st = 'refer' >>> if st == st[: : -1]: # st == st.reverse() does the same thing print st, 'is a palindrome' else: print st, 'is not a palindrome' Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
  • 99. hour 1: Python 101 strings palindrome checking A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal, Panama!’ Often it’s allowed to skip over spaces and punctuation marks It’s a classic problem while dealing with strings. And we’ll stick to character-unit palindromes. Example: redivider, noon, radar, madam, refer, etc. We’ll see a simple one liner code that checks if a string is a palindrome. >>> st = 'refer' >>> if st == st[: : -1]: # st == st.reverse() does the same thing print st, 'is a palindrome' else: print st, 'is not a palindrome' Satyaki Sikdar© Programming in Python April 22 2016 28 / 137
  • 100. hour 1: Python 101 strings multi-line strings and escape characters Multi-line strings Multi-line strings are different from ordinary strings. As the name suggests, they can span over multiple lines Enclosed by a pair of ”’ or """ They support all the string operations - indexing, slicing and dicing... End of lines are marked with the EOL (n) character Escape characters acts as the escape character "I am 5'11" tall." # escape double-quote inside the string 'I am 5'11" tall.' # escape single-quote inside the string Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
  • 101. hour 1: Python 101 strings multi-line strings and escape characters Multi-line strings Multi-line strings are different from ordinary strings. As the name suggests, they can span over multiple lines Enclosed by a pair of ”’ or """ They support all the string operations - indexing, slicing and dicing... End of lines are marked with the EOL (n) character Escape characters acts as the escape character "I am 5'11" tall." # escape double-quote inside the string 'I am 5'11" tall.' # escape single-quote inside the string Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
  • 102. hour 1: Python 101 strings multi-line strings and escape characters Multi-line strings Multi-line strings are different from ordinary strings. As the name suggests, they can span over multiple lines Enclosed by a pair of ”’ or """ They support all the string operations - indexing, slicing and dicing... End of lines are marked with the EOL (n) character Escape characters acts as the escape character "I am 5'11" tall." # escape double-quote inside the string 'I am 5'11" tall.' # escape single-quote inside the string Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
  • 103. hour 1: Python 101 strings multi-line strings and escape characters Multi-line strings Multi-line strings are different from ordinary strings. As the name suggests, they can span over multiple lines Enclosed by a pair of ”’ or """ They support all the string operations - indexing, slicing and dicing... End of lines are marked with the EOL (n) character Escape characters acts as the escape character "I am 5'11" tall." # escape double-quote inside the string 'I am 5'11" tall.' # escape single-quote inside the string Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
  • 104. hour 1: Python 101 strings multi-line strings and escape characters Multi-line strings Multi-line strings are different from ordinary strings. As the name suggests, they can span over multiple lines Enclosed by a pair of ”’ or """ They support all the string operations - indexing, slicing and dicing... End of lines are marked with the EOL (n) character Escape characters acts as the escape character "I am 5'11" tall." # escape double-quote inside the string 'I am 5'11" tall.' # escape single-quote inside the string Satyaki Sikdar© Programming in Python April 22 2016 29 / 137
  • 105. hour 1: Python 101 strings the Boolean data type They represent the logical True and False. The operations that they support are as follows: Negation: Using the word not before True or False negates it. >>> not True yields False and >>> not False yields True Logical and: The result is True if and only if every argument is True. In Python, use the word and Logical or: The result is False if and only if every argument is False. In Python, use the word or Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
  • 106. hour 1: Python 101 strings the Boolean data type They represent the logical True and False. The operations that they support are as follows: Negation: Using the word not before True or False negates it. >>> not True yields False and >>> not False yields True Logical and: The result is True if and only if every argument is True. In Python, use the word and Logical or: The result is False if and only if every argument is False. In Python, use the word or Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
  • 107. hour 1: Python 101 strings the Boolean data type They represent the logical True and False. The operations that they support are as follows: Negation: Using the word not before True or False negates it. >>> not True yields False and >>> not False yields True Logical and: The result is True if and only if every argument is True. In Python, use the word and Logical or: The result is False if and only if every argument is False. In Python, use the word or Satyaki Sikdar© Programming in Python April 22 2016 30 / 137
  • 108. hour 1: Python 101 strings truth tables for logical and and logical or A B A or B A and B False False False False False True True False True False True False True True True True Satyaki Sikdar© Programming in Python April 22 2016 31 / 137
  • 109. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 110. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 111. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 112. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 113. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 114. hour 1: Python 101 strings logical comparisons The comparisons yield either True or False Equals (==): 2 == 3 is False Not equal (!=): 2 != 3 is True Greater than (>): 2 > 3 is False Lesser than (<): 2 < 3 is True Greater than or equal to (>=): 2 >= 4 is False Lesser than or equal to (<=): 2 <= 4 is True Satyaki Sikdar© Programming in Python April 22 2016 32 / 137
  • 115. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 116. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 117. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 118. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 119. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 120. hour 1: Python 101 variables and bindings variables! Variables provide a way to associate names with objects I personally prefer under_bars over camelCase. It’s up to you to decide A variable is just a name. An object can have one, more than one or no names associated with it. Assignment statements are used to assign values to variables. a = 15 Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’ and it’ll be alright! Note: julia, Julia, and JULIA are all different Satyaki Sikdar© Programming in Python April 22 2016 33 / 137
  • 121. hour 1: Python 101 variables and bindings bindings Consider the code pi = 3.14159 radius = 11.2 area = pi * (radius ** 2) radius = 14.3 Figure: Binding of variables to objects Satyaki Sikdar© Programming in Python April 22 2016 34 / 137
  • 122. hour 1: Python 101 variables and bindings meaningful names! a = 3.14159 b = 11.2 c = a * (b ** 2) pi = 3.14159 diameter = 11.2 area = pi * (diameter ** 2) The two codes to Python are exactly the same To a human, they are pretty different! The code on the right is better, but there’s a problem?! The variable should have been called radius instead of diameter, or the area formula is wrong! Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
  • 123. hour 1: Python 101 variables and bindings meaningful names! a = 3.14159 b = 11.2 c = a * (b ** 2) pi = 3.14159 diameter = 11.2 area = pi * (diameter ** 2) The two codes to Python are exactly the same To a human, they are pretty different! The code on the right is better, but there’s a problem?! The variable should have been called radius instead of diameter, or the area formula is wrong! Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
  • 124. hour 1: Python 101 variables and bindings meaningful names! a = 3.14159 b = 11.2 c = a * (b ** 2) pi = 3.14159 diameter = 11.2 area = pi * (diameter ** 2) The two codes to Python are exactly the same To a human, they are pretty different! The code on the right is better, but there’s a problem?! The variable should have been called radius instead of diameter, or the area formula is wrong! Satyaki Sikdar© Programming in Python April 22 2016 35 / 137
  • 125. hour 1: Python 101 variables and bindings a comic from xkcd.com Satyaki Sikdar© Programming in Python April 22 2016 36 / 137
  • 126. hour 1: Python 101 variables and bindings the names which must not be given! and as assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield Satyaki Sikdar© Programming in Python April 22 2016 37 / 137
  • 127. hour 1: Python 101 basic i/o taking input from the user! name = raw_input('Enter something!') print name #example output: Edwin print type(name) #example output: <type 'str'> Satyaki Sikdar© Programming in Python April 22 2016 38 / 137
  • 128. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 129. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 130. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 131. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 132. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 133. hour 1: Python 101 basic i/o raw_input returns a string What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer 12 float(’12.4’) gives 12.4 (a float) int(’12.4’) makes it 12 (an integer) float(12) makes it 12.0 (a float) Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError Satyaki Sikdar© Programming in Python April 22 2016 39 / 137
  • 134. hour 2: ifs, buts and repeats conditionals Satyaki Sikdar© Programming in Python April 22 2016 40 / 137
  • 135. hour 2: ifs, buts and repeats conditionals making decisions Making decisions are an integral part of our lives. Thus, it becomes essential for our codes to make decisions too! Python has if, else and elif to help your code make decisions The syntax is as follows if boolean_expression1: do_something elif boolean_expression2: do_something_different else: do_something_else Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
  • 136. hour 2: ifs, buts and repeats conditionals making decisions Making decisions are an integral part of our lives. Thus, it becomes essential for our codes to make decisions too! Python has if, else and elif to help your code make decisions The syntax is as follows if boolean_expression1: do_something elif boolean_expression2: do_something_different else: do_something_else Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
  • 137. hour 2: ifs, buts and repeats conditionals making decisions Making decisions are an integral part of our lives. Thus, it becomes essential for our codes to make decisions too! Python has if, else and elif to help your code make decisions The syntax is as follows if boolean_expression1: do_something elif boolean_expression2: do_something_different else: do_something_else Satyaki Sikdar© Programming in Python April 22 2016 41 / 137
  • 138. hour 2: ifs, buts and repeats conditionals a simple illustration I Comparing the values of two variables x = int(raw_input('Enter 1st number')) y = int(raw_input('Enter 2nd number')) if x == y: print 'the numbers are equal' elif x > y: print 'the first number is bigger' else: print 'the second number is bigger' Satyaki Sikdar© Programming in Python April 22 2016 42 / 137
  • 139. hour 2: ifs, buts and repeats conditionals a simple illustration II Nested conditionals Divisibility by 6 x = int(raw_input("Enter a number: ")) if x % 2 == 0: if x % 3 == 0: print 'Divisible by both 2 and 3' else: print 'Divisible by 2, but not by 3' elif x % 3 == 0: print 'Divisible by 3 and not by 2' else: print 'Divisible by neither 2 nor 3' Satyaki Sikdar© Programming in Python April 22 2016 43 / 137
  • 140. hour 2: ifs, buts and repeats conditionals the in keyword The in keyword is used for containment checking Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False Thus in can be used in if, elif statements. Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
  • 141. hour 2: ifs, buts and repeats conditionals the in keyword The in keyword is used for containment checking Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False Thus in can be used in if, elif statements. Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
  • 142. hour 2: ifs, buts and repeats conditionals the in keyword The in keyword is used for containment checking Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ian botham’ returns True, but ’beefy’ in ’sir ian botham’ returns False Thus in can be used in if, elif statements. Satyaki Sikdar© Programming in Python April 22 2016 44 / 137
  • 143. hour 2: ifs, buts and repeats looping constructs loops: the basic idea Satyaki Sikdar© Programming in Python April 22 2016 45 / 137
  • 144. hour 2: ifs, buts and repeats looping constructs say hello to while loops while loops in Python are no different than the while loops in other common languages. Phew! It’s similar to a conditional statement. But, no else blocks As long as the condition is valid, the loop body keeps executing. The condition is re-evaluated each time Let’s look at an example. # squaring an integer, the hard way >>> x = 4 >>> ans = 0 >>> iters_left = x >>> while iters_left != 0: ans = ans + x iters_left = iters_left - 1 >>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
  • 145. hour 2: ifs, buts and repeats looping constructs say hello to while loops while loops in Python are no different than the while loops in other common languages. Phew! It’s similar to a conditional statement. But, no else blocks As long as the condition is valid, the loop body keeps executing. The condition is re-evaluated each time Let’s look at an example. # squaring an integer, the hard way >>> x = 4 >>> ans = 0 >>> iters_left = x >>> while iters_left != 0: ans = ans + x iters_left = iters_left - 1 >>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
  • 146. hour 2: ifs, buts and repeats looping constructs say hello to while loops while loops in Python are no different than the while loops in other common languages. Phew! It’s similar to a conditional statement. But, no else blocks As long as the condition is valid, the loop body keeps executing. The condition is re-evaluated each time Let’s look at an example. # squaring an integer, the hard way >>> x = 4 >>> ans = 0 >>> iters_left = x >>> while iters_left != 0: ans = ans + x iters_left = iters_left - 1 >>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137
  • 147. hour 2: ifs, buts and repeats looping constructs squaring the hard way taking x = 4 as an example test # x ans iters_left iters_left != 0 1 4 0 4 True 2 4 4 3 True 3 4 8 2 True 4 4 12 1 True 5 4 16 0 False Boom! When iters_left is 0, we have our answer in ans For what values of x will the program terminate? Satyaki Sikdar© Programming in Python April 22 2016 47 / 137
  • 148. hour 2: ifs, buts and repeats looping constructs the correctness of the program It’s very important to check if the procedure works for all x We’ve already proved that it works when x is a positive integer What about when x is 0? It works! The body of the while loop is not executed. So, ans stays at 0! What about when x is negative? Let’s see! Say x = -3. test # x ans iters_left iters_left != 0 1 -3 0 -3 True 2 -3 -3 -4 True 3 -3 -6 -5 True 4 -3 -9 -6 True 5 -3 -12 -7 True 6 -3 -15 -8 True OOPS! It hasn’t stop when it’s supposed to! :( Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
  • 149. hour 2: ifs, buts and repeats looping constructs the correctness of the program It’s very important to check if the procedure works for all x We’ve already proved that it works when x is a positive integer What about when x is 0? It works! The body of the while loop is not executed. So, ans stays at 0! What about when x is negative? Let’s see! Say x = -3. test # x ans iters_left iters_left != 0 1 -3 0 -3 True 2 -3 -3 -4 True 3 -3 -6 -5 True 4 -3 -9 -6 True 5 -3 -12 -7 True 6 -3 -15 -8 True OOPS! It hasn’t stop when it’s supposed to! :( Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
  • 150. hour 2: ifs, buts and repeats looping constructs the correctness of the program It’s very important to check if the procedure works for all x We’ve already proved that it works when x is a positive integer What about when x is 0? It works! The body of the while loop is not executed. So, ans stays at 0! What about when x is negative? Let’s see! Say x = -3. test # x ans iters_left iters_left != 0 1 -3 0 -3 True 2 -3 -3 -4 True 3 -3 -6 -5 True 4 -3 -9 -6 True 5 -3 -12 -7 True 6 -3 -15 -8 True OOPS! It hasn’t stop when it’s supposed to! :( Satyaki Sikdar© Programming in Python April 22 2016 48 / 137
  • 151. hour 2: ifs, buts and repeats looping constructs does the code ever end??!! Things start to get a little fishy when x is negative Does the program ever end? NO!! Is it a problem? YES !! Is there any way to fix this? Hell yeah! Let’s see the code. >>> x = -4 >>> ans = 0 >>> iters_left = abs(x) #the absolute value of x >>> while iters_left != 0: ans = ans + abs(x) iters_left = iters_left - 1 >>> print x, 'squared is', ans Does it make things better? Yes indeed! We got a working program that squares all integers! Yay! Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
  • 152. hour 2: ifs, buts and repeats looping constructs does the code ever end??!! Things start to get a little fishy when x is negative Does the program ever end? NO!! Is it a problem? YES !! Is there any way to fix this? Hell yeah! Let’s see the code. >>> x = -4 >>> ans = 0 >>> iters_left = abs(x) #the absolute value of x >>> while iters_left != 0: ans = ans + abs(x) iters_left = iters_left - 1 >>> print x, 'squared is', ans Does it make things better? Yes indeed! We got a working program that squares all integers! Yay! Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
  • 153. hour 2: ifs, buts and repeats looping constructs does the code ever end??!! Things start to get a little fishy when x is negative Does the program ever end? NO!! Is it a problem? YES !! Is there any way to fix this? Hell yeah! Let’s see the code. >>> x = -4 >>> ans = 0 >>> iters_left = abs(x) #the absolute value of x >>> while iters_left != 0: ans = ans + abs(x) iters_left = iters_left - 1 >>> print x, 'squared is', ans Does it make things better? Yes indeed! We got a working program that squares all integers! Yay! Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
  • 154. hour 2: ifs, buts and repeats looping constructs does the code ever end??!! Things start to get a little fishy when x is negative Does the program ever end? NO!! Is it a problem? YES !! Is there any way to fix this? Hell yeah! Let’s see the code. >>> x = -4 >>> ans = 0 >>> iters_left = abs(x) #the absolute value of x >>> while iters_left != 0: ans = ans + abs(x) iters_left = iters_left - 1 >>> print x, 'squared is', ans Does it make things better? Yes indeed! We got a working program that squares all integers! Yay! Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
  • 155. hour 2: ifs, buts and repeats looping constructs does the code ever end??!! Things start to get a little fishy when x is negative Does the program ever end? NO!! Is it a problem? YES !! Is there any way to fix this? Hell yeah! Let’s see the code. >>> x = -4 >>> ans = 0 >>> iters_left = abs(x) #the absolute value of x >>> while iters_left != 0: ans = ans + abs(x) iters_left = iters_left - 1 >>> print x, 'squared is', ans Does it make things better? Yes indeed! We got a working program that squares all integers! Yay! Satyaki Sikdar© Programming in Python April 22 2016 49 / 137
  • 156. hour 2: ifs, buts and repeats looping constructs for loops In Python, for loops are a little different. They are effectively for each loops Syntax: for item in iterable: code block #notice the indentation Strings are iterable. So are lists, tuples, dictionaries, sets, ... Example: >>> st = 'cuts like a knife!' >>> for x in st: print x, >>> cuts like a knife! Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
  • 157. hour 2: ifs, buts and repeats looping constructs for loops In Python, for loops are a little different. They are effectively for each loops Syntax: for item in iterable: code block #notice the indentation Strings are iterable. So are lists, tuples, dictionaries, sets, ... Example: >>> st = 'cuts like a knife!' >>> for x in st: print x, >>> cuts like a knife! Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
  • 158. hour 2: ifs, buts and repeats looping constructs for loops In Python, for loops are a little different. They are effectively for each loops Syntax: for item in iterable: code block #notice the indentation Strings are iterable. So are lists, tuples, dictionaries, sets, ... Example: >>> st = 'cuts like a knife!' >>> for x in st: print x, >>> cuts like a knife! Satyaki Sikdar© Programming in Python April 22 2016 50 / 137
  • 159. hour 2: ifs, buts and repeats looping constructs how does it work? for item in iterable: code block for each item (x) in the iterable, execute the code block repeatedly as long as the iterable is not exhausted. You may or may not use the item (x). # figuring out the length of a string w/o using len() >>> length = 0 >>> st = 'rocky mountain high' >>> for c in st: length += 1 >>> print 'the length of the string is', length Output: the length of the string is 19 Satyaki Sikdar© Programming in Python April 22 2016 51 / 137
  • 160. hour 2: ifs, buts and repeats looping constructs a few more illustrations This time we’ll use the item in the for loop >>> st = 'rocky mountain high' >>> for c in st: if c == 'o': print c.upper(), else: print c, >>> rOcky mOuntain high >>> st = 'Ryan ten Doeschate' >>> for c in st[: : -1]: print c, >>> etahcseoD net nayR Satyaki Sikdar© Programming in Python April 22 2016 52 / 137
  • 161. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 162. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 163. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 164. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 165. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 166. hour 2: ifs, buts and repeats looping constructs the xrange function An arithmetic series (AP) has parameters start, stop and step xrange() is used to generate an iterator for an AP in Python xrange(start, stop, step) will generate numbers of the form: start, start + step, start + 2 ∗ step, ..., in the set [start, end) If one argument (x) is passed, start = 0, stop = x, step = 1 >>> for no in xrange(5): print no, #output: 0 1 2 3 4 If two arguments (x, y) are passed, start = x, stop = y, step = 1 >>> for no in xrange(2, 5): print no, #output: 2 3 4 If three (x, y, z) are passed, start = x, stop = y, step = z >>> for no in xrange(1, 6, 2): print no, #output 1 3 5Satyaki Sikdar© Programming in Python April 22 2016 53 / 137
  • 167. hour 2: ifs, buts and repeats looping constructs loop condition evaluation >>> x = 4 >>> for j in range(x): for i in range(x): print i x = 2 0 1 2 3 0 1 0 1 0 1 Seems bizarre? Let’s break it down The first range function is evaluated once with x = 4, so come what may, the outer loop will run 4 times Each time, the inner loop would run x times, so the first time it runs 4 times But inside, x becomes 2, and then from second time on, the inner loop runs twice Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
  • 168. hour 2: ifs, buts and repeats looping constructs loop condition evaluation >>> x = 4 >>> for j in range(x): for i in range(x): print i x = 2 0 1 2 3 0 1 0 1 0 1 Seems bizarre? Let’s break it down The first range function is evaluated once with x = 4, so come what may, the outer loop will run 4 times Each time, the inner loop would run x times, so the first time it runs 4 times But inside, x becomes 2, and then from second time on, the inner loop runs twice Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
  • 169. hour 2: ifs, buts and repeats looping constructs loop condition evaluation >>> x = 4 >>> for j in range(x): for i in range(x): print i x = 2 0 1 2 3 0 1 0 1 0 1 Seems bizarre? Let’s break it down The first range function is evaluated once with x = 4, so come what may, the outer loop will run 4 times Each time, the inner loop would run x times, so the first time it runs 4 times But inside, x becomes 2, and then from second time on, the inner loop runs twice Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
  • 170. hour 2: ifs, buts and repeats looping constructs loop condition evaluation >>> x = 4 >>> for j in range(x): for i in range(x): print i x = 2 0 1 2 3 0 1 0 1 0 1 Seems bizarre? Let’s break it down The first range function is evaluated once with x = 4, so come what may, the outer loop will run 4 times Each time, the inner loop would run x times, so the first time it runs 4 times But inside, x becomes 2, and then from second time on, the inner loop runs twice Satyaki Sikdar© Programming in Python April 22 2016 54 / 137
  • 171. hour 2: ifs, buts and repeats bisection search bisection search - the hunt for √ x >>> x = int(raw_input("Enter a number")) >>> eps = 0.01; num_guess = 0 >>> low = 0.0 >>> high = x >>> ans = (low + high) / 2.0 >>> while abs(ans ** 2 - x) >= eps: print 'guess:', num_guess, 'low:', low, 'high:', high, 'ans:', ans num_guess += 1 if ans ** 2 < x: low = ans else: high = ans ans = (low + high) / 2.0 >>> print ans, 'is close to sqrt of', x Satyaki Sikdar© Programming in Python April 22 2016 55 / 137
  • 172. hour 2: ifs, buts and repeats floating points floating point woes >>> x = 0.0 >>> for i in xrange(10): x = x + 0.1 >>> if x == 1.0: print x, '= 1.0' >>> else: print x, 'is not 1.0' The output? 1.0 is not 1.0 What on earth is going on? Has Python gone nuts? Let’s dig deeper. In the memory, every number is stored in binary. Let’s try to figure out what’s the binary representation for (a) (0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2 (0.1)10 = (?)2? What about 3 32 = 0.9375? How about 25 256? Turns out, no matter how many bits you use, you can’t have a perfect 0.1 in memory! So round up!! So, now we know that x at the end is not a perfect 1, so the equality test fails But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t alway the actual value Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
  • 173. hour 2: ifs, buts and repeats floating points floating point woes >>> x = 0.0 >>> for i in xrange(10): x = x + 0.1 >>> if x == 1.0: print x, '= 1.0' >>> else: print x, 'is not 1.0' The output? 1.0 is not 1.0 What on earth is going on? Has Python gone nuts? Let’s dig deeper. In the memory, every number is stored in binary. Let’s try to figure out what’s the binary representation for (a) (0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2 (0.1)10 = (?)2? What about 3 32 = 0.9375? How about 25 256? Turns out, no matter how many bits you use, you can’t have a perfect 0.1 in memory! So round up!! So, now we know that x at the end is not a perfect 1, so the equality test fails But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t alway the actual value Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
  • 174. hour 2: ifs, buts and repeats floating points floating point woes >>> x = 0.0 >>> for i in xrange(10): x = x + 0.1 >>> if x == 1.0: print x, '= 1.0' >>> else: print x, 'is not 1.0' The output? 1.0 is not 1.0 What on earth is going on? Has Python gone nuts? Let’s dig deeper. In the memory, every number is stored in binary. Let’s try to figure out what’s the binary representation for (a) (0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2 (0.1)10 = (?)2? What about 3 32 = 0.9375? How about 25 256? Turns out, no matter how many bits you use, you can’t have a perfect 0.1 in memory! So round up!! So, now we know that x at the end is not a perfect 1, so the equality test fails But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t alway the actual value Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
  • 175. hour 2: ifs, buts and repeats floating points floating point woes >>> x = 0.0 >>> for i in xrange(10): x = x + 0.1 >>> if x == 1.0: print x, '= 1.0' >>> else: print x, 'is not 1.0' The output? 1.0 is not 1.0 What on earth is going on? Has Python gone nuts? Let’s dig deeper. In the memory, every number is stored in binary. Let’s try to figure out what’s the binary representation for (a) (0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2 (0.1)10 = (?)2? What about 3 32 = 0.9375? How about 25 256? Turns out, no matter how many bits you use, you can’t have a perfect 0.1 in memory! So round up!! So, now we know that x at the end is not a perfect 1, so the equality test fails But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t alway the actual value Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
  • 176. hour 2: ifs, buts and repeats floating points floating point woes >>> x = 0.0 >>> for i in xrange(10): x = x + 0.1 >>> if x == 1.0: print x, '= 1.0' >>> else: print x, 'is not 1.0' The output? 1.0 is not 1.0 What on earth is going on? Has Python gone nuts? Let’s dig deeper. In the memory, every number is stored in binary. Let’s try to figure out what’s the binary representation for (a) (0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2 (0.1)10 = (?)2? What about 3 32 = 0.9375? How about 25 256? Turns out, no matter how many bits you use, you can’t have a perfect 0.1 in memory! So round up!! So, now we know that x at the end is not a perfect 1, so the equality test fails But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’t alway the actual value Satyaki Sikdar© Programming in Python April 22 2016 56 / 137
  • 177. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 178. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 179. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 180. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 181. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 182. hour 3: data structures 101 lists lists The list is a container that holds a number of other objects, in a given order. Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable Lists are enclosed in square brackets [ ] and the elements are separated by commas. Example: [1, 2, 3, 5] is a valid list It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list Lists support indexing and slicing in the exact same manner as strings do. They also support + and *. So, [1, 2] + [3, 4] => [1, 2, 3, 4] and [1, 2] * 3 => [1, 2, 1, 2, 1, 2] Satyaki Sikdar© Programming in Python April 22 2016 57 / 137
  • 183. hour 3: data structures 101 list operations basic functions and operations Empty list is declared as [ ] or list() len() gives you the length of the list. So, len([1, 5, 6]) gives 3 lst[i] returns the item at index i (the first item has index 0) Lists, unlike strings, support item assignment >>> lst = [1, 3, 4] >>> lst[1] = 7 >>> print lst >>> print lst [1, 3, 4] [1, 7, 4] Adding a new element to a list is done using append >>> lst = [1, 3, 4] >>> lst.append(10) >>> print lst >>> print lst [1, 3, 4] [1, 3, 4, 10] Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
  • 184. hour 3: data structures 101 list operations basic functions and operations Empty list is declared as [ ] or list() len() gives you the length of the list. So, len([1, 5, 6]) gives 3 lst[i] returns the item at index i (the first item has index 0) Lists, unlike strings, support item assignment >>> lst = [1, 3, 4] >>> lst[1] = 7 >>> print lst >>> print lst [1, 3, 4] [1, 7, 4] Adding a new element to a list is done using append >>> lst = [1, 3, 4] >>> lst.append(10) >>> print lst >>> print lst [1, 3, 4] [1, 3, 4, 10] Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
  • 185. hour 3: data structures 101 list operations basic functions and operations Empty list is declared as [ ] or list() len() gives you the length of the list. So, len([1, 5, 6]) gives 3 lst[i] returns the item at index i (the first item has index 0) Lists, unlike strings, support item assignment >>> lst = [1, 3, 4] >>> lst[1] = 7 >>> print lst >>> print lst [1, 3, 4] [1, 7, 4] Adding a new element to a list is done using append >>> lst = [1, 3, 4] >>> lst.append(10) >>> print lst >>> print lst [1, 3, 4] [1, 3, 4, 10] Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
  • 186. hour 3: data structures 101 list operations basic functions and operations Empty list is declared as [ ] or list() len() gives you the length of the list. So, len([1, 5, 6]) gives 3 lst[i] returns the item at index i (the first item has index 0) Lists, unlike strings, support item assignment >>> lst = [1, 3, 4] >>> lst[1] = 7 >>> print lst >>> print lst [1, 3, 4] [1, 7, 4] Adding a new element to a list is done using append >>> lst = [1, 3, 4] >>> lst.append(10) >>> print lst >>> print lst [1, 3, 4] [1, 3, 4, 10] Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
  • 187. hour 3: data structures 101 list operations basic functions and operations Empty list is declared as [ ] or list() len() gives you the length of the list. So, len([1, 5, 6]) gives 3 lst[i] returns the item at index i (the first item has index 0) Lists, unlike strings, support item assignment >>> lst = [1, 3, 4] >>> lst[1] = 7 >>> print lst >>> print lst [1, 3, 4] [1, 7, 4] Adding a new element to a list is done using append >>> lst = [1, 3, 4] >>> lst.append(10) >>> print lst >>> print lst [1, 3, 4] [1, 3, 4, 10] Satyaki Sikdar© Programming in Python April 22 2016 58 / 137
  • 188. hour 3: data structures 101 list operations Append adds one element at a time. lst.append(1, 2) would raise an error! So, what if we want to append more than one items? It’s called extending a list >>> lst = [1, 5, 9] >>> #what if we use + instead? >>> print lst >>> lst2 = [8, 9, 10] [1, 5, 9] >>> lst3 = lst2 + [3, 4] >>> lst.extend([2, 5, 10]) >>> print lst3 >>> print lst [8, 9, 10, 3, 4] [1, 5, 9, 2, 5, 10] Satyaki Sikdar© Programming in Python April 22 2016 59 / 137
  • 189. hour 3: data structures 101 list operations Append adds one element at a time. lst.append(1, 2) would raise an error! So, what if we want to append more than one items? It’s called extending a list >>> lst = [1, 5, 9] >>> #what if we use + instead? >>> print lst >>> lst2 = [8, 9, 10] [1, 5, 9] >>> lst3 = lst2 + [3, 4] >>> lst.extend([2, 5, 10]) >>> print lst3 >>> print lst [8, 9, 10, 3, 4] [1, 5, 9, 2, 5, 10] Satyaki Sikdar© Programming in Python April 22 2016 59 / 137
  • 190. hour 3: data structures 101 list operations Append adds a new element only to the end Insert gives more flexibility. It allows you to specify the position as well Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by lst.insert(0, x), and at the end by lst.insert(len(lst), x) What about removing things? lst.pop() removes and returns the last element. lst.pop(pos) removes the element from a specific position. >>> lst = [1, 2, 3, 4, 5] >>> print lst.pop() >>> print lst 5 [1, 2, 3, 4, 5] >>> print lst >>> lst.insert(2, 10) [1, 2, 10, 3, 4] >>> print lst >>> print lst.pop(3) [1, 2, 10, 3, 4, 5] 3 Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
  • 191. hour 3: data structures 101 list operations Append adds a new element only to the end Insert gives more flexibility. It allows you to specify the position as well Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by lst.insert(0, x), and at the end by lst.insert(len(lst), x) What about removing things? lst.pop() removes and returns the last element. lst.pop(pos) removes the element from a specific position. >>> lst = [1, 2, 3, 4, 5] >>> print lst.pop() >>> print lst 5 [1, 2, 3, 4, 5] >>> print lst >>> lst.insert(2, 10) [1, 2, 10, 3, 4] >>> print lst >>> print lst.pop(3) [1, 2, 10, 3, 4, 5] 3 Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
  • 192. hour 3: data structures 101 list operations Append adds a new element only to the end Insert gives more flexibility. It allows you to specify the position as well Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by lst.insert(0, x), and at the end by lst.insert(len(lst), x) What about removing things? lst.pop() removes and returns the last element. lst.pop(pos) removes the element from a specific position. >>> lst = [1, 2, 3, 4, 5] >>> print lst.pop() >>> print lst 5 [1, 2, 3, 4, 5] >>> print lst >>> lst.insert(2, 10) [1, 2, 10, 3, 4] >>> print lst >>> print lst.pop(3) [1, 2, 10, 3, 4, 5] 3 Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
  • 193. hour 3: data structures 101 list operations Append adds a new element only to the end Insert gives more flexibility. It allows you to specify the position as well Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done by lst.insert(0, x), and at the end by lst.insert(len(lst), x) What about removing things? lst.pop() removes and returns the last element. lst.pop(pos) removes the element from a specific position. >>> lst = [1, 2, 3, 4, 5] >>> print lst.pop() >>> print lst 5 [1, 2, 3, 4, 5] >>> print lst >>> lst.insert(2, 10) [1, 2, 10, 3, 4] >>> print lst >>> print lst.pop(3) [1, 2, 10, 3, 4, 5] 3 Satyaki Sikdar© Programming in Python April 22 2016 60 / 137
  • 194. hour 3: data structures 101 list operations some more functions of lists list.remove(x): Remove the first item from the list whose value is x list.index(x): Return the index in the list of the first item whose value is x. list.count(x): Return the number of times x appears in the list. list.reverse(): Reverses the list in place list.sort(): Sorts the list in place in ascending order. For descending order, do list.sort(reverse = True) Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
  • 195. hour 3: data structures 101 list operations some more functions of lists list.remove(x): Remove the first item from the list whose value is x list.index(x): Return the index in the list of the first item whose value is x. list.count(x): Return the number of times x appears in the list. list.reverse(): Reverses the list in place list.sort(): Sorts the list in place in ascending order. For descending order, do list.sort(reverse = True) Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
  • 196. hour 3: data structures 101 list operations some more functions of lists list.remove(x): Remove the first item from the list whose value is x list.index(x): Return the index in the list of the first item whose value is x. list.count(x): Return the number of times x appears in the list. list.reverse(): Reverses the list in place list.sort(): Sorts the list in place in ascending order. For descending order, do list.sort(reverse = True) Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
  • 197. hour 3: data structures 101 list operations some more functions of lists list.remove(x): Remove the first item from the list whose value is x list.index(x): Return the index in the list of the first item whose value is x. list.count(x): Return the number of times x appears in the list. list.reverse(): Reverses the list in place list.sort(): Sorts the list in place in ascending order. For descending order, do list.sort(reverse = True) Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
  • 198. hour 3: data structures 101 list operations some more functions of lists list.remove(x): Remove the first item from the list whose value is x list.index(x): Return the index in the list of the first item whose value is x. list.count(x): Return the number of times x appears in the list. list.reverse(): Reverses the list in place list.sort(): Sorts the list in place in ascending order. For descending order, do list.sort(reverse = True) Satyaki Sikdar© Programming in Python April 22 2016 61 / 137
  • 199. hour 3: data structures 101 list comprehension list comprehension and range() range() works exactly in the same fashion as xrange(), just with one difference; range() produces a list with all the elements in the sequence >>> l = range(2, 10, 3) >>> print l [2, 5, 8] List comprehensions are a short-hand way of making lists >>> squares = [] >>> squares = [x ** 2 for x in xrange(6)] >>> for x in xrange(6): >>> print squares squares.append(x ** 2) [0, 1, 4, 9, 16, 25] >>> print squares [0, 1, 4, 9, 16, 25] Satyaki Sikdar© Programming in Python April 22 2016 62 / 137
  • 200. hour 3: data structures 101 list comprehension list comprehension and range() range() works exactly in the same fashion as xrange(), just with one difference; range() produces a list with all the elements in the sequence >>> l = range(2, 10, 3) >>> print l [2, 5, 8] List comprehensions are a short-hand way of making lists >>> squares = [] >>> squares = [x ** 2 for x in xrange(6)] >>> for x in xrange(6): >>> print squares squares.append(x ** 2) [0, 1, 4, 9, 16, 25] >>> print squares [0, 1, 4, 9, 16, 25] Satyaki Sikdar© Programming in Python April 22 2016 62 / 137
  • 201. hour 3: data structures 101 tuples A tuple is a sequence of values. Enclosed by parentheses The values can be any type, and they are indexed by integers, so, tuples are a lot like lists However, tuples are immutable >>> t = 'a', 'b', 'c', 'd', 'e' >>> print t ('a', 'b', 'c', 'd', 'e') >>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise >>> t2 = 'a', #to create a tuple with one element, use the comma >>> print t2 ('a') Another way to create a tuple is the built-in function tuple >>> t = tuple() >>> t1 = tuple('dutch') >>> print t >>> print t1 () ('d', 'u', 't', 'c', 'h') Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
  • 202. hour 3: data structures 101 tuples A tuple is a sequence of values. Enclosed by parentheses The values can be any type, and they are indexed by integers, so, tuples are a lot like lists However, tuples are immutable >>> t = 'a', 'b', 'c', 'd', 'e' >>> print t ('a', 'b', 'c', 'd', 'e') >>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise >>> t2 = 'a', #to create a tuple with one element, use the comma >>> print t2 ('a') Another way to create a tuple is the built-in function tuple >>> t = tuple() >>> t1 = tuple('dutch') >>> print t >>> print t1 () ('d', 'u', 't', 'c', 'h') Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
  • 203. hour 3: data structures 101 tuples A tuple is a sequence of values. Enclosed by parentheses The values can be any type, and they are indexed by integers, so, tuples are a lot like lists However, tuples are immutable >>> t = 'a', 'b', 'c', 'd', 'e' >>> print t ('a', 'b', 'c', 'd', 'e') >>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise >>> t2 = 'a', #to create a tuple with one element, use the comma >>> print t2 ('a') Another way to create a tuple is the built-in function tuple >>> t = tuple() >>> t1 = tuple('dutch') >>> print t >>> print t1 () ('d', 'u', 't', 'c', 'h') Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
  • 204. hour 3: data structures 101 tuples A tuple is a sequence of values. Enclosed by parentheses The values can be any type, and they are indexed by integers, so, tuples are a lot like lists However, tuples are immutable >>> t = 'a', 'b', 'c', 'd', 'e' >>> print t ('a', 'b', 'c', 'd', 'e') >>> t1 = ('a', 'b', 'c', 'd', 'e') #common practise >>> t2 = 'a', #to create a tuple with one element, use the comma >>> print t2 ('a') Another way to create a tuple is the built-in function tuple >>> t = tuple() >>> t1 = tuple('dutch') >>> print t >>> print t1 () ('d', 'u', 't', 'c', 'h') Satyaki Sikdar© Programming in Python April 22 2016 63 / 137
  • 205. hour 3: data structures 101 tuple operations Most list operators also work on tuples. The bracket operator indexes an element >>> t = ('a', 'b', 'c', 'd', 'e') >>> print t[0] a Slice operator selects a range of elements. >>> print t[1: 3] ('b', 'c') Try to modify one of the elements of the tuple, you get an error >>> t[0] = 'A' TypeError: object doesn't support item assignment Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
  • 206. hour 3: data structures 101 tuple operations Most list operators also work on tuples. The bracket operator indexes an element >>> t = ('a', 'b', 'c', 'd', 'e') >>> print t[0] a Slice operator selects a range of elements. >>> print t[1: 3] ('b', 'c') Try to modify one of the elements of the tuple, you get an error >>> t[0] = 'A' TypeError: object doesn't support item assignment Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
  • 207. hour 3: data structures 101 tuple operations Most list operators also work on tuples. The bracket operator indexes an element >>> t = ('a', 'b', 'c', 'd', 'e') >>> print t[0] a Slice operator selects a range of elements. >>> print t[1: 3] ('b', 'c') Try to modify one of the elements of the tuple, you get an error >>> t[0] = 'A' TypeError: object doesn't support item assignment Satyaki Sikdar© Programming in Python April 22 2016 64 / 137
  • 208. hour 3: data structures 101 tuple operations packing and unpacking tuples With conventional assignments, you have to use a temp variable >>> temp = a >>> a = b >>> b = temp This solution is cumbersome; tuple assignment is more elegant >>> a, b = b, a The left side is a tuple of variables, the right side is a tuple of expressions The number of variables on the left and the number of values on the right have to be the same: >>> a, b = 1, 2, 3 ValueError: too many values to unpack Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
  • 209. hour 3: data structures 101 tuple operations packing and unpacking tuples With conventional assignments, you have to use a temp variable >>> temp = a >>> a = b >>> b = temp This solution is cumbersome; tuple assignment is more elegant >>> a, b = b, a The left side is a tuple of variables, the right side is a tuple of expressions The number of variables on the left and the number of values on the right have to be the same: >>> a, b = 1, 2, 3 ValueError: too many values to unpack Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
  • 210. hour 3: data structures 101 tuple operations packing and unpacking tuples With conventional assignments, you have to use a temp variable >>> temp = a >>> a = b >>> b = temp This solution is cumbersome; tuple assignment is more elegant >>> a, b = b, a The left side is a tuple of variables, the right side is a tuple of expressions The number of variables on the left and the number of values on the right have to be the same: >>> a, b = 1, 2, 3 ValueError: too many values to unpack Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
  • 211. hour 3: data structures 101 tuple operations packing and unpacking tuples With conventional assignments, you have to use a temp variable >>> temp = a >>> a = b >>> b = temp This solution is cumbersome; tuple assignment is more elegant >>> a, b = b, a The left side is a tuple of variables, the right side is a tuple of expressions The number of variables on the left and the number of values on the right have to be the same: >>> a, b = 1, 2, 3 ValueError: too many values to unpack Satyaki Sikdar© Programming in Python April 22 2016 65 / 137
  • 212. hour 3: data structures 101 tuple operations lists and tuples zip takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence >>> s = 'abc' >>> t = [0, 1, 2] >>> zip(s, t) [('a, 0), ('b', 1), ('c', 2)] If the sequences are not the same length, the result has the length of the shorter one >>> zip('Ned', 'Sansa', 'Bran') [('N', 'S', 'B'), ('e', 'a', 'r'), ('d', 'n', 'a')] Satyaki Sikdar© Programming in Python April 22 2016 66 / 137
  • 213. hour 3: data structures 101 tuple operations lists and tuples zip takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence >>> s = 'abc' >>> t = [0, 1, 2] >>> zip(s, t) [('a, 0), ('b', 1), ('c', 2)] If the sequences are not the same length, the result has the length of the shorter one >>> zip('Ned', 'Sansa', 'Bran') [('N', 'S', 'B'), ('e', 'a', 'r'), ('d', 'n', 'a')] Satyaki Sikdar© Programming in Python April 22 2016 66 / 137
  • 214. hour 3: data structures 101 tuple operations You can use tuple assignment in a for loop to traverse a list of tuples: t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print number, letter 0 a 1 b 2 c Combine zip, for and tuple assignment to traverse two (or more) sequences def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False To traverse the elements of a sequence and their indices, use enumerate: >>> for idx, ele in enumerate('abc'): print idx, ele Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
  • 215. hour 3: data structures 101 tuple operations You can use tuple assignment in a for loop to traverse a list of tuples: t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print number, letter 0 a 1 b 2 c Combine zip, for and tuple assignment to traverse two (or more) sequences def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False To traverse the elements of a sequence and their indices, use enumerate: >>> for idx, ele in enumerate('abc'): print idx, ele Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
  • 216. hour 3: data structures 101 tuple operations You can use tuple assignment in a for loop to traverse a list of tuples: t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print number, letter 0 a 1 b 2 c Combine zip, for and tuple assignment to traverse two (or more) sequences def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False To traverse the elements of a sequence and their indices, use enumerate: >>> for idx, ele in enumerate('abc'): print idx, ele Satyaki Sikdar© Programming in Python April 22 2016 67 / 137
  • 217. hour 3: data structures 101 tuple operations tuple comparisons The relational operators work with tuples and other seqs Python starts by comparing the first element from each seq. If they are equal, it goes on to the next elements, and so on >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True The sort function works the same way >>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)] >>> l.sort() >>> print l [(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)] Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
  • 218. hour 3: data structures 101 tuple operations tuple comparisons The relational operators work with tuples and other seqs Python starts by comparing the first element from each seq. If they are equal, it goes on to the next elements, and so on >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True The sort function works the same way >>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)] >>> l.sort() >>> print l [(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)] Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
  • 219. hour 3: data structures 101 tuple operations tuple comparisons The relational operators work with tuples and other seqs Python starts by comparing the first element from each seq. If they are equal, it goes on to the next elements, and so on >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True The sort function works the same way >>> l = [(4, 0, 0), (0, 1, 2), (2, 3, 5), (2, 3, 4)] >>> l.sort() >>> print l [(0, 1, 2), (2, 3, 4), (2, 3, 5), (4, 0, 0)] Satyaki Sikdar© Programming in Python April 22 2016 68 / 137
  • 220. hour 3: data structures 101 functions functions We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and so on.. Python allows you to make your own functions! YAY! Each function definition is of the form def name of function (list_of_parameters): body of the function return things A function can return things too! And in Python, every function returns something. You can tell the function to return something that you want! By default it’s None Notice there’s no mention of the return type Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
  • 221. hour 3: data structures 101 functions functions We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and so on.. Python allows you to make your own functions! YAY! Each function definition is of the form def name of function (list_of_parameters): body of the function return things A function can return things too! And in Python, every function returns something. You can tell the function to return something that you want! By default it’s None Notice there’s no mention of the return type Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
  • 222. hour 3: data structures 101 functions functions We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and so on.. Python allows you to make your own functions! YAY! Each function definition is of the form def name of function (list_of_parameters): body of the function return things A function can return things too! And in Python, every function returns something. You can tell the function to return something that you want! By default it’s None Notice there’s no mention of the return type Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
  • 223. hour 3: data structures 101 functions functions We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and so on.. Python allows you to make your own functions! YAY! Each function definition is of the form def name of function (list_of_parameters): body of the function return things A function can return things too! And in Python, every function returns something. You can tell the function to return something that you want! By default it’s None Notice there’s no mention of the return type Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
  • 224. hour 3: data structures 101 functions functions We’ve already used some pre-defined functions already! len(), range(), abs(), count(), and so on.. Python allows you to make your own functions! YAY! Each function definition is of the form def name of function (list_of_parameters): body of the function return things A function can return things too! And in Python, every function returns something. You can tell the function to return something that you want! By default it’s None Notice there’s no mention of the return type Satyaki Sikdar© Programming in Python April 22 2016 69 / 137
  • 225. hour 3: data structures 101 an example An easy example def maximum(x, y): ''' returns the maximum of the two arguments ''' if x > y: return x else: return y >>> print maximum(10, 20) 20 A function can have any name (barring the reserved words) x and y are called formal parameters. The values (10, 20) are called actual parameters. Function calls expect you to feed in the arguments, throws a nasty TypeError otherwise Satyaki Sikdar© Programming in Python April 22 2016 70 / 137
  • 226. hour 3: data structures 101 an example An easy example def maximum(x, y): ''' returns the maximum of the two arguments ''' if x > y: return x else: return y >>> print maximum(10, 20) 20 A function can have any name (barring the reserved words) x and y are called formal parameters. The values (10, 20) are called actual parameters. Function calls expect you to feed in the arguments, throws a nasty TypeError otherwise Satyaki Sikdar© Programming in Python April 22 2016 70 / 137
  • 227. hour 3: data structures 101 flow of control flow of control in a function 1 The expressions that make up the actual parameters are evaluated. If the call is maximum(5 + 7, 7 * 2), the arguments are evaluated first 2 The point of execution moves to the first line of the function 3 The code in the body of the function is executed until a return statement is encountered or when there are no more lines to execute in the function body 4 The value of invocation is returned back to the point of calling 5 The point of execution transfers back to the point of invocation It’s up to the user to use the value that’s returned. Satyaki Sikdar© Programming in Python April 22 2016 71 / 137
  • 228. hour 3: data structures 101 keyword arguments Arguments and default values There are two ways how formal parameters get bound to actual parameters 1 Positional: the first formal parameter is bound to the actual parameter, the second formal to the second actual and so on 2 Keyword arguments: formals are bound to actuals using the name of the formal parameter def print_name(first_name, last_name, reverse): if reverse: print last_name + ', ' + first_name else: print first_name, last_name >>> print_name('Hugh', 'Jackman', False) #prints Hugh Jackman >>> print_name('Hugh', 'Jackman', reverse = False) >>> print_name('Hugh', last_name = 'Jackman', reverse = False) Satyaki Sikdar© Programming in Python April 22 2016 72 / 137
  • 229. hour 3: data structures 101 keyword arguments arguments contd. The order of the keyword arguments does not matter. So, print_name(last_name = ’Jackman’, first_name = ’Hugh’, reverse = False) is valid But, you can’t follow up a keyword argument with a non keyword argument. That confuses the interpreter, and it throws an error. So, print_name(first_name = ’Hugh’, ’Jackman’, False) is not valid Satyaki Sikdar© Programming in Python April 22 2016 73 / 137
  • 230. hour 3: data structures 101 keyword arguments arguments contd. The order of the keyword arguments does not matter. So, print_name(last_name = ’Jackman’, first_name = ’Hugh’, reverse = False) is valid But, you can’t follow up a keyword argument with a non keyword argument. That confuses the interpreter, and it throws an error. So, print_name(first_name = ’Hugh’, ’Jackman’, False) is not valid Satyaki Sikdar© Programming in Python April 22 2016 73 / 137
  • 231. hour 3: data structures 101 scope scope of variables in functions def f(x): #x is a formal parameter y = 1 x = x + y print 'x = ', x return x >>> x = 3 >>> y = 2 >>> z = f(x) #x is an actual parameter >>> print ';z = %s, x = %s, y = %s' % (z, x, y) x = 4; z = 4, x = 3, y = 2 Satyaki Sikdar© Programming in Python April 22 2016 74 / 137
  • 232. hour 3: data structures 101 scope so what’s going on here? Surely, x is surely misbehaving?! Or is it? the two x’s are not really the same! They might have the same name, but they are different! Kinda like how you find someone on facebook with your name but then that person has nothing to do with you! The concept of name space comes into play The variables in the function f exist only when f is executing. When the control returns back from the function, it goes back to the variables defined previously. Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
  • 233. hour 3: data structures 101 scope so what’s going on here? Surely, x is surely misbehaving?! Or is it? the two x’s are not really the same! They might have the same name, but they are different! Kinda like how you find someone on facebook with your name but then that person has nothing to do with you! The concept of name space comes into play The variables in the function f exist only when f is executing. When the control returns back from the function, it goes back to the variables defined previously. Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
  • 234. hour 3: data structures 101 scope so what’s going on here? Surely, x is surely misbehaving?! Or is it? the two x’s are not really the same! They might have the same name, but they are different! Kinda like how you find someone on facebook with your name but then that person has nothing to do with you! The concept of name space comes into play The variables in the function f exist only when f is executing. When the control returns back from the function, it goes back to the variables defined previously. Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
  • 235. hour 3: data structures 101 scope so what’s going on here? Surely, x is surely misbehaving?! Or is it? the two x’s are not really the same! They might have the same name, but they are different! Kinda like how you find someone on facebook with your name but then that person has nothing to do with you! The concept of name space comes into play The variables in the function f exist only when f is executing. When the control returns back from the function, it goes back to the variables defined previously. Satyaki Sikdar© Programming in Python April 22 2016 75 / 137
  • 236. hour 3: data structures 101 scope returning a bunch of things Python allows functions to return more than one thing def funky_func(x): return x ** 2, x ** 3 >>> funky_func(3) (9, 27) #things are returned as a tuple >>> a, b = funky_func(3) #unpacking the tuple >>> print a 9 >>> print b 27 This paradigm, though simple, is very powerful Satyaki Sikdar© Programming in Python April 22 2016 76 / 137
  • 237. hour 3: data structures 101 scope returning a bunch of things Python allows functions to return more than one thing def funky_func(x): return x ** 2, x ** 3 >>> funky_func(3) (9, 27) #things are returned as a tuple >>> a, b = funky_func(3) #unpacking the tuple >>> print a 9 >>> print b 27 This paradigm, though simple, is very powerful Satyaki Sikdar© Programming in Python April 22 2016 76 / 137
  • 238. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 239. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 240. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 241. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 242. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 243. hour 3: data structures 101 sets set A set is an unordered collection of distinct, immutable values { Alice , 3.1415, Carol } is a set of 3 elements { Dean } is a singleton set >>> cset = {11, 11, 22} >>> cset set([11, 22]) Sets are mutable - can add or remove things on the fly Insertion using add Deletion using remove or discard >>> st = {'Jon', 'Arya'} >>> st.add('Jaime') >>> st.remove('Jon') >>> print st >>> print st set(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime']) Satyaki Sikdar© Programming in Python April 22 2016 77 / 137
  • 244. hour 3: data structures 101 set operations set operations Sets in Python support all common set operations >>> test_team = {'Cook', 'Root', 'Stokes', 'Ali', 'Broad'} >>> odi_team = {'Hales', 'Roy', 'Root', 'Ali', 'Stokes'} >>> >>> print test_team | odi_team #set union set(['Stokes', 'Hales', 'Ali', 'Broad', 'Roy', 'Cook', 'Root']) >>> print test_team & odi_team #set intersection set(['Stokes', 'Root', 'Ali']) >>> test_team - odi_team #set differnce set(['Cook', 'Broad']) >>> test_team ^ odi_team #symmetric difference set(['Hales', 'Broad', 'Roy', 'Cook']) Satyaki Sikdar© Programming in Python April 22 2016 78 / 137
  • 245. hour 3: data structures 101 set operations set operations Sets do not support indexing! >>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'} >>> myset set(['Toronto', 'Amsterdam', 'Winnipeg']) >>> myset[0] TypeError: 'set' object does not support indexing + operator doesn’t work with sets >>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'} >>> myset2 = {'Brussels', 'Hamilton'} >>> myset1 + myset2 TypeError: unsupported operand type(s) for +: 'set' and 'set' Satyaki Sikdar© Programming in Python April 22 2016 79 / 137
  • 246. hour 3: data structures 101 set operations set operations Sets do not support indexing! >>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'} >>> myset set(['Toronto', 'Amsterdam', 'Winnipeg']) >>> myset[0] TypeError: 'set' object does not support indexing + operator doesn’t work with sets >>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'} >>> myset2 = {'Brussels', 'Hamilton'} >>> myset1 + myset2 TypeError: unsupported operand type(s) for +: 'set' and 'set' Satyaki Sikdar© Programming in Python April 22 2016 79 / 137
  • 247. hour 3: data structures 101 dictionaries dictionary A dictionary is like a list, but more general - a personal favorite In a list, the indices have to be integers; in a dictionary they can be (almost) any type The keys must be immutable Let’s build a dictionary that maps from English to Spanish words. Keys and values are both strings >>> eng2sp = dict() # or eng2sp = {} >>> print eng2sp {} Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
  • 248. hour 3: data structures 101 dictionaries dictionary A dictionary is like a list, but more general - a personal favorite In a list, the indices have to be integers; in a dictionary they can be (almost) any type The keys must be immutable Let’s build a dictionary that maps from English to Spanish words. Keys and values are both strings >>> eng2sp = dict() # or eng2sp = {} >>> print eng2sp {} Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
  • 249. hour 3: data structures 101 dictionaries dictionary A dictionary is like a list, but more general - a personal favorite In a list, the indices have to be integers; in a dictionary they can be (almost) any type The keys must be immutable Let’s build a dictionary that maps from English to Spanish words. Keys and values are both strings >>> eng2sp = dict() # or eng2sp = {} >>> print eng2sp {} Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
  • 250. hour 3: data structures 101 dictionaries dictionary A dictionary is like a list, but more general - a personal favorite In a list, the indices have to be integers; in a dictionary they can be (almost) any type The keys must be immutable Let’s build a dictionary that maps from English to Spanish words. Keys and values are both strings >>> eng2sp = dict() # or eng2sp = {} >>> print eng2sp {} Satyaki Sikdar© Programming in Python April 22 2016 80 / 137
  • 251. hour 3: data structures 101 dictionary manipulations To add items to the dictionary, use square brackets >>> eng2sp['one'] = 'uno' Creates an item that maps from the key ’one’ to the value ’uno’ >>> print eng2sp {'one': 'uno'} Instantiate a dictionary with multiple items like >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'} The order of key-value pairs is not the same Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
  • 252. hour 3: data structures 101 dictionary manipulations To add items to the dictionary, use square brackets >>> eng2sp['one'] = 'uno' Creates an item that maps from the key ’one’ to the value ’uno’ >>> print eng2sp {'one': 'uno'} Instantiate a dictionary with multiple items like >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'} The order of key-value pairs is not the same Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
  • 253. hour 3: data structures 101 dictionary manipulations To add items to the dictionary, use square brackets >>> eng2sp['one'] = 'uno' Creates an item that maps from the key ’one’ to the value ’uno’ >>> print eng2sp {'one': 'uno'} Instantiate a dictionary with multiple items like >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'} The order of key-value pairs is not the same Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
  • 254. hour 3: data structures 101 dictionary manipulations To add items to the dictionary, use square brackets >>> eng2sp['one'] = 'uno' Creates an item that maps from the key ’one’ to the value ’uno’ >>> print eng2sp {'one': 'uno'} Instantiate a dictionary with multiple items like >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'} The order of key-value pairs is not the same Satyaki Sikdar© Programming in Python April 22 2016 81 / 137
  • 255. hour 3: data structures 101 dictionary manipulations constraints on keys and values Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys Ints, floats, strings, tuples, frozensets are fine! There’s no constraint on the nature of values >>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'], 'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'], 'Greyjoy': ['Theon', 'Yara', 'Balon']} >>> print house_members['Greyjoy'] ['Theon', 'Yara', 'Balon'] Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
  • 256. hour 3: data structures 101 dictionary manipulations constraints on keys and values Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys Ints, floats, strings, tuples, frozensets are fine! There’s no constraint on the nature of values >>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'], 'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'], 'Greyjoy': ['Theon', 'Yara', 'Balon']} >>> print house_members['Greyjoy'] ['Theon', 'Yara', 'Balon'] Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
  • 257. hour 3: data structures 101 dictionary manipulations constraints on keys and values Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys Ints, floats, strings, tuples, frozensets are fine! There’s no constraint on the nature of values >>> house_members = {'Stark': ['Ned', 'Robb', 'Jon', 'Sansa', 'Arya'], 'Lannister': ['Tyrion', 'Tywin', 'Cersei', 'Jaime'], 'Greyjoy': ['Theon', 'Yara', 'Balon']} >>> print house_members['Greyjoy'] ['Theon', 'Yara', 'Balon'] Satyaki Sikdar© Programming in Python April 22 2016 82 / 137
  • 258. hour 3: data structures 101 dictionary manipulations Indexing is done solely using the keys >>> print eng2sp['two'] dos If the key isn’t in the dictionary, you get an exception >>> print eng2sp['four'] KeyError: 'four' len function returns the number of key-value pairs >>> len(eng2sp) 3 in tells you whether something appears as a key in the dictionary (appearing as a value is not good enough) >>> 'one' in eng2sp >>> 'uno' in eng2sp True False Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
  • 259. hour 3: data structures 101 dictionary manipulations Indexing is done solely using the keys >>> print eng2sp['two'] dos If the key isn’t in the dictionary, you get an exception >>> print eng2sp['four'] KeyError: 'four' len function returns the number of key-value pairs >>> len(eng2sp) 3 in tells you whether something appears as a key in the dictionary (appearing as a value is not good enough) >>> 'one' in eng2sp >>> 'uno' in eng2sp True False Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
  • 260. hour 3: data structures 101 dictionary manipulations Indexing is done solely using the keys >>> print eng2sp['two'] dos If the key isn’t in the dictionary, you get an exception >>> print eng2sp['four'] KeyError: 'four' len function returns the number of key-value pairs >>> len(eng2sp) 3 in tells you whether something appears as a key in the dictionary (appearing as a value is not good enough) >>> 'one' in eng2sp >>> 'uno' in eng2sp True False Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
  • 261. hour 3: data structures 101 dictionary manipulations Indexing is done solely using the keys >>> print eng2sp['two'] dos If the key isn’t in the dictionary, you get an exception >>> print eng2sp['four'] KeyError: 'four' len function returns the number of key-value pairs >>> len(eng2sp) 3 in tells you whether something appears as a key in the dictionary (appearing as a value is not good enough) >>> 'one' in eng2sp >>> 'uno' in eng2sp True False Satyaki Sikdar© Programming in Python April 22 2016 83 / 137
  • 262. hour 3: data structures 101 dictionary manipulations deleting things A specific key can be deleted from a dictionary by using pop >>> eng2sp {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> eng2sp.pop('two') 'dos' >>> eng2sp {'one': 'uno', 'three': 'tres'} A key at random can be deleted by using popitem >>> eng2sp {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> eng2sp.popitem() ('three', 'tres') Satyaki Sikdar© Programming in Python April 22 2016 84 / 137
  • 263. hour 3: data structures 101 dictionary manipulations deleting things A specific key can be deleted from a dictionary by using pop >>> eng2sp {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> eng2sp.pop('two') 'dos' >>> eng2sp {'one': 'uno', 'three': 'tres'} A key at random can be deleted by using popitem >>> eng2sp {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> eng2sp.popitem() ('three', 'tres') Satyaki Sikdar© Programming in Python April 22 2016 84 / 137
  • 264. hour 3: data structures 101 dictionary manipulations Dicts have a method called items that returns a list of tuples of key-value pairs >>> d = {'a': 0, 'b': 1, 'c': 2} >>> t = d.items() >>> print t [('a', 0), ('c', 2), ('b', 1)] Going in the other way, you can use a list of tuples to init a new dict >>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> print d {'a': 0, 'c': 2, 'b': 1} Combining dict with zip yields a concise way >>> d = dict(zip('abc', range(3))) >>> print d {'a': 0, 'c': 2, 'b': 1} Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
  • 265. hour 3: data structures 101 dictionary manipulations Dicts have a method called items that returns a list of tuples of key-value pairs >>> d = {'a': 0, 'b': 1, 'c': 2} >>> t = d.items() >>> print t [('a', 0), ('c', 2), ('b', 1)] Going in the other way, you can use a list of tuples to init a new dict >>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> print d {'a': 0, 'c': 2, 'b': 1} Combining dict with zip yields a concise way >>> d = dict(zip('abc', range(3))) >>> print d {'a': 0, 'c': 2, 'b': 1} Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
  • 266. hour 3: data structures 101 dictionary manipulations Dicts have a method called items that returns a list of tuples of key-value pairs >>> d = {'a': 0, 'b': 1, 'c': 2} >>> t = d.items() >>> print t [('a', 0), ('c', 2), ('b', 1)] Going in the other way, you can use a list of tuples to init a new dict >>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> print d {'a': 0, 'c': 2, 'b': 1} Combining dict with zip yields a concise way >>> d = dict(zip('abc', range(3))) >>> print d {'a': 0, 'c': 2, 'b': 1} Satyaki Sikdar© Programming in Python April 22 2016 85 / 137
  • 267. hour 3: data structures 101 counters counters Given a string and you want to count how many times each letter appears 1 create 26 variables, one for each letter of the alphabet 2 create a list with 26 elements. Then convert each character to a number and use it as an index into the list 3 create a dict with characters as keys and counters as the values def hist(st): counter = dict() for c in st: if c not in counter: counter[c] = 1 else: counter[c] += 1 return counter >>> print hist('brontosaurus') {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
  • 268. hour 3: data structures 101 counters counters Given a string and you want to count how many times each letter appears 1 create 26 variables, one for each letter of the alphabet 2 create a list with 26 elements. Then convert each character to a number and use it as an index into the list 3 create a dict with characters as keys and counters as the values def hist(st): counter = dict() for c in st: if c not in counter: counter[c] = 1 else: counter[c] += 1 return counter >>> print hist('brontosaurus') {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
  • 269. hour 3: data structures 101 counters counters Given a string and you want to count how many times each letter appears 1 create 26 variables, one for each letter of the alphabet 2 create a list with 26 elements. Then convert each character to a number and use it as an index into the list 3 create a dict with characters as keys and counters as the values def hist(st): counter = dict() for c in st: if c not in counter: counter[c] = 1 else: counter[c] += 1 return counter >>> print hist('brontosaurus') {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
  • 270. hour 3: data structures 101 counters counters Given a string and you want to count how many times each letter appears 1 create 26 variables, one for each letter of the alphabet 2 create a list with 26 elements. Then convert each character to a number and use it as an index into the list 3 create a dict with characters as keys and counters as the values def hist(st): counter = dict() for c in st: if c not in counter: counter[c] = 1 else: counter[c] += 1 return counter >>> print hist('brontosaurus') {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}Satyaki Sikdar© Programming in Python April 22 2016 86 / 137
  • 271. hour 3: data structures 101 counters inverting a dictionary Given a dict that maps letters to freq, create a dict that maps freq to letters Several letters may have the same freq, so each value must be a list def inv_dict(d): inv = {} for key in d: val = d[key] if val not in inv: #we haven't seen the value so far inv[val] = [key] else: inv[val].append(key) return val >>> h = hist('parrot') >>> print inv_dict(h) >>> print h {1: ['a', 'p', 't', 'o'], 2: ['r']} {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1} Satyaki Sikdar© Programming in Python April 22 2016 87 / 137
  • 272. hour 3: data structures 101 counters inverting a dictionary Given a dict that maps letters to freq, create a dict that maps freq to letters Several letters may have the same freq, so each value must be a list def inv_dict(d): inv = {} for key in d: val = d[key] if val not in inv: #we haven't seen the value so far inv[val] = [key] else: inv[val].append(key) return val >>> h = hist('parrot') >>> print inv_dict(h) >>> print h {1: ['a', 'p', 't', 'o'], 2: ['r']} {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1} Satyaki Sikdar© Programming in Python April 22 2016 87 / 137
  • 273. hour 4: confusion 101 recursion Satyaki Sikdar© Programming in Python April 22 2016 88 / 137
  • 274. hour 4: confusion 101 introduction what is it anyway? It’s a method where the solution to a problem depends on solutions to smaller instances of the same problem Some problems are inherently recursive Let’s see an example. The legal code of the US defines a natural born citizen roughly as follows: Any child born inside the United States Any child born in wedlock outside the United States both of whose parents are citizens of the US, as long as one parent has lived in the US prior to the birth of the child, and Any child born in wedlock outside the US one of whose parents is a US citizen who has lived at least five years, .... so on Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
  • 275. hour 4: confusion 101 introduction what is it anyway? It’s a method where the solution to a problem depends on solutions to smaller instances of the same problem Some problems are inherently recursive Let’s see an example. The legal code of the US defines a natural born citizen roughly as follows: Any child born inside the United States Any child born in wedlock outside the United States both of whose parents are citizens of the US, as long as one parent has lived in the US prior to the birth of the child, and Any child born in wedlock outside the US one of whose parents is a US citizen who has lived at least five years, .... so on Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
  • 276. hour 4: confusion 101 introduction what is it anyway? It’s a method where the solution to a problem depends on solutions to smaller instances of the same problem Some problems are inherently recursive Let’s see an example. The legal code of the US defines a natural born citizen roughly as follows: Any child born inside the United States Any child born in wedlock outside the United States both of whose parents are citizens of the US, as long as one parent has lived in the US prior to the birth of the child, and Any child born in wedlock outside the US one of whose parents is a US citizen who has lived at least five years, .... so on Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
  • 277. hour 4: confusion 101 introduction what is it anyway? It’s a method where the solution to a problem depends on solutions to smaller instances of the same problem Some problems are inherently recursive Let’s see an example. The legal code of the US defines a natural born citizen roughly as follows: Any child born inside the United States Any child born in wedlock outside the United States both of whose parents are citizens of the US, as long as one parent has lived in the US prior to the birth of the child, and Any child born in wedlock outside the US one of whose parents is a US citizen who has lived at least five years, .... so on Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
  • 278. hour 4: confusion 101 introduction what is it anyway? It’s a method where the solution to a problem depends on solutions to smaller instances of the same problem Some problems are inherently recursive Let’s see an example. The legal code of the US defines a natural born citizen roughly as follows: Any child born inside the United States Any child born in wedlock outside the United States both of whose parents are citizens of the US, as long as one parent has lived in the US prior to the birth of the child, and Any child born in wedlock outside the US one of whose parents is a US citizen who has lived at least five years, .... so on Satyaki Sikdar© Programming in Python April 22 2016 89 / 137
  • 279. hour 4: confusion 101 the structure The structure of a generic recursive code def rec_function(parameters): if bool_expr1: # base case 1 return something if bool_expr2: # base case 2 return something_else do_something_funky inductive_case #call rec_function() with reduced parameters IMPORTANT: 1 The base cases must terminate the flow of code and return something meaningful 2 The inductive case must be called for the reduced problem, such that it reaches the base case sometime Satyaki Sikdar© Programming in Python April 22 2016 90 / 137
  • 280. hour 4: confusion 101 illustrations example 1 Mathematically, n! = n ∗ (n − 1)! if n > 1 1 otherwise def factR(n): ''' computes n! recursively n >=0 ''' if n <= 1: return 1 else: return n * factorial(n - 1) def factI(n): ''' computes n! iteratively n >=0 ''' result = 1 while n > 1: result = result * n n -= 1 return result Satyaki Sikdar© Programming in Python April 22 2016 91 / 137
  • 281. hour 4: confusion 101 illustrations how does it work? Say you are calling factorial(3). Let’s see what happens! factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2) factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1) factorial(1) is called. Hits the base case! No further calls to factorial. Time to track back. factorial(1) returns 1 factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2) returns 2 x 1 factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3 x 2 => 6 And we are done! Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
  • 282. hour 4: confusion 101 illustrations how does it work? Say you are calling factorial(3). Let’s see what happens! factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2) factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1) factorial(1) is called. Hits the base case! No further calls to factorial. Time to track back. factorial(1) returns 1 factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2) returns 2 x 1 factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3 x 2 => 6 And we are done! Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
  • 283. hour 4: confusion 101 illustrations how does it work? Say you are calling factorial(3). Let’s see what happens! factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2) factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1) factorial(1) is called. Hits the base case! No further calls to factorial. Time to track back. factorial(1) returns 1 factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2) returns 2 x 1 factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3 x 2 => 6 And we are done! Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
  • 284. hour 4: confusion 101 illustrations how does it work? Say you are calling factorial(3). Let’s see what happens! factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2) factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1) factorial(1) is called. Hits the base case! No further calls to factorial. Time to track back. factorial(1) returns 1 factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2) returns 2 x 1 factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3 x 2 => 6 And we are done! Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
  • 285. hour 4: confusion 101 illustrations how does it work? Say you are calling factorial(3). Let’s see what happens! factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2) factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1) factorial(1) is called. Hits the base case! No further calls to factorial. Time to track back. factorial(1) returns 1 factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2) returns 2 x 1 factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3 x 2 => 6 And we are done! Satyaki Sikdar© Programming in Python April 22 2016 92 / 137
  • 286. hour 4: confusion 101 recursion woes base cases gone wrong! n! = (n+1)! n+1 if n > 0 1 otherwise Although this seems valid, but there lies a problem. Look at the base case! Will it ever be reached? If we implement this function, we will get a run time error. Let’s see what it is. Satyaki Sikdar© Programming in Python April 22 2016 93 / 137
  • 287. hour 4: confusion 101 recursion woes implementation def factorial(n): if n == 0: return 1 else: return factorial(n + 1) / (n + 1) >>> factorial(4) => Something nasty! RuntimeError: maximum recursion depth exceeded It’s no surprise that factorial(4) fails. The same thing happens whenever the argument is non zero. So, who’s to blame? The innocent looking recurrence relation? Yeah Satyaki Sikdar© Programming in Python April 22 2016 94 / 137
  • 288. hour 4: confusion 101 recursion woes implementation def factorial(n): if n == 0: return 1 else: return factorial(n + 1) / (n + 1) >>> factorial(4) => Something nasty! RuntimeError: maximum recursion depth exceeded It’s no surprise that factorial(4) fails. The same thing happens whenever the argument is non zero. So, who’s to blame? The innocent looking recurrence relation? Yeah Satyaki Sikdar© Programming in Python April 22 2016 94 / 137
  • 289. hour 4: confusion 101 recursion woes how to fix this mess?! Can the base case ever be reached with n > 0 ? NO! So, as a consequence, the program doesn’t stop until you run out of stack space! Stack overflow is the recursive equivalent to an infinite loop in iteration Fix the recurrence relation to get the correct results. Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
  • 290. hour 4: confusion 101 recursion woes how to fix this mess?! Can the base case ever be reached with n > 0 ? NO! So, as a consequence, the program doesn’t stop until you run out of stack space! Stack overflow is the recursive equivalent to an infinite loop in iteration Fix the recurrence relation to get the correct results. Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
  • 291. hour 4: confusion 101 recursion woes how to fix this mess?! Can the base case ever be reached with n > 0 ? NO! So, as a consequence, the program doesn’t stop until you run out of stack space! Stack overflow is the recursive equivalent to an infinite loop in iteration Fix the recurrence relation to get the correct results. Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
  • 292. hour 4: confusion 101 recursion woes how to fix this mess?! Can the base case ever be reached with n > 0 ? NO! So, as a consequence, the program doesn’t stop until you run out of stack space! Stack overflow is the recursive equivalent to an infinite loop in iteration Fix the recurrence relation to get the correct results. Satyaki Sikdar© Programming in Python April 22 2016 95 / 137
  • 293. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 294. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 295. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 296. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 297. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 298. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 299. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 300. hour 4: confusion 101 fibonacci numbers they breed like bunnies! Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terrible assumptions The assumptions Bunnies are able to mate when they are 1 month old They have a 1 month gestation period They are immortal Each female gives birth to one male and one female bunnies every time Two bunnies, a male and a female are put in an exhibit The question is, how many pregnant bunnies would there be at the end of say n months? Month n Females Fn 0 1 1 1 2 2 3 3 4 5 5 8 6 13 Satyaki Sikdar© Programming in Python April 22 2016 96 / 137
  • 301. hour 4: confusion 101 fibonacci numbers Fibonacci numbers Fn =    Fn−1 + Fn−2 n 2 1 n = 1 0 n = 0 def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: return fibo(n - 1) + fibo(n - 2) Satyaki Sikdar© Programming in Python April 22 2016 97 / 137
  • 302. hour 4: confusion 101 recursion tree recursion tree Figure: Recursion tree for fib(7) Satyaki Sikdar© Programming in Python April 22 2016 98 / 137
  • 303. hour 4: confusion 101 speeding up speed of computation Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why? Let’s take another look at the recursion tree Aren’t we doing the same calculations in between? Is there a better way? Hell yeah! Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
  • 304. hour 4: confusion 101 speeding up speed of computation Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why? Let’s take another look at the recursion tree Aren’t we doing the same calculations in between? Is there a better way? Hell yeah! Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
  • 305. hour 4: confusion 101 speeding up speed of computation Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why? Let’s take another look at the recursion tree Aren’t we doing the same calculations in between? Is there a better way? Hell yeah! Satyaki Sikdar© Programming in Python April 22 2016 99 / 137
  • 306. hour 4: confusion 101 speeding up a bottom-up approach def fib_v2(n): ans = [0, 1] for i in xrange(2, n + 1): ans.append(ans[i - 1] + ans[i - 2]) return ans[n] Is this approach better? YES! Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2 calls to the ans list. Try calculating the 40th Fibonacci number again! Much faster, isn’t it? Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
  • 307. hour 4: confusion 101 speeding up a bottom-up approach def fib_v2(n): ans = [0, 1] for i in xrange(2, n + 1): ans.append(ans[i - 1] + ans[i - 2]) return ans[n] Is this approach better? YES! Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2 calls to the ans list. Try calculating the 40th Fibonacci number again! Much faster, isn’t it? Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
  • 308. hour 4: confusion 101 speeding up a bottom-up approach def fib_v2(n): ans = [0, 1] for i in xrange(2, n + 1): ans.append(ans[i - 1] + ans[i - 2]) return ans[n] Is this approach better? YES! Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2 calls to the ans list. Try calculating the 40th Fibonacci number again! Much faster, isn’t it? Satyaki Sikdar© Programming in Python April 22 2016 100 / 137
  • 309. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 310. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 311. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 312. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 313. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 314. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 315. hour 5: oops-a-daisy intro to OOP object oriented programming So far, we have seen a lot of Python’s own data structures and types. What if we need specialized structures which are not natively provided in Py? We have the power of defining our own type! Let’s see an example. Say we want to represent a point in 2-D space. What are our options? Store the coordinates x and y in two variables x and y Store the coordinates as elements in a list or tuple Create a new type to represent points as specialized things called objects Creating a new type is (a little) more complicated than the other options, but it has advantages that will be apparent soon Satyaki Sikdar© Programming in Python April 22 2016 101 / 137
  • 316. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 317. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 318. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 319. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 320. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 321. hour 5: oops-a-daisy class classes A user-defined type is also called a class. A class defintion looks like this class Point: """Represents a point in 2-D space.""" This header indicates that the new class is a Point The body is a docstring that explains what the class is for We can define variables and functions inside a class definition The class is like a factory for creating objects To create a Point, you call Point as if it were a function. It is called instantiation and the object is an instance of the class >>> blank = Point() >>> print blank <__main__.Point instance at 0xb7e9d3ac> Satyaki Sikdar© Programming in Python April 22 2016 102 / 137
  • 322. hour 5: oops-a-daisy class attributes You can assign values to an instance using dot notation >>> blank.x = 3.0 >>> blank.y = 4.0 You can read the value of an attribute using the same syntax >>> print blank.y 4.0 >>> x = blank.x >>> print x 3.0 Figure: Object diagram The expression blank.x means, “Go to the object blank refers to and get the value of x” In this case, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
  • 323. hour 5: oops-a-daisy class attributes You can assign values to an instance using dot notation >>> blank.x = 3.0 >>> blank.y = 4.0 You can read the value of an attribute using the same syntax >>> print blank.y 4.0 >>> x = blank.x >>> print x 3.0 Figure: Object diagram The expression blank.x means, “Go to the object blank refers to and get the value of x” In this case, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
  • 324. hour 5: oops-a-daisy class attributes You can assign values to an instance using dot notation >>> blank.x = 3.0 >>> blank.y = 4.0 You can read the value of an attribute using the same syntax >>> print blank.y 4.0 >>> x = blank.x >>> print x 3.0 Figure: Object diagram The expression blank.x means, “Go to the object blank refers to and get the value of x” In this case, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
  • 325. hour 5: oops-a-daisy class attributes You can assign values to an instance using dot notation >>> blank.x = 3.0 >>> blank.y = 4.0 You can read the value of an attribute using the same syntax >>> print blank.y 4.0 >>> x = blank.x >>> print x 3.0 Figure: Object diagram The expression blank.x means, “Go to the object blank refers to and get the value of x” In this case, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x Satyaki Sikdar© Programming in Python April 22 2016 103 / 137
  • 326. hour 5: oops-a-daisy class If you try to access an attribute that doesn’t exist, you get an AttributeError If you are not sure what type an object is, you can use the type function If you are not sure whether an object has a particular attribute, you can use the built-in function hasattr >>> p = Point() >>> p.x = 5.5 >>> p.y = 2.2 >>> print p.x 5.5 >>> print p.y 2.2 >>> print p.z AttributeError: Point instance has no attribute 'z' >>> type(p) <type '__main__'.Point'> >>> hasattr(p, 'x') True >>> hasattr(p, 'z') False Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
  • 327. hour 5: oops-a-daisy class If you try to access an attribute that doesn’t exist, you get an AttributeError If you are not sure what type an object is, you can use the type function If you are not sure whether an object has a particular attribute, you can use the built-in function hasattr >>> p = Point() >>> p.x = 5.5 >>> p.y = 2.2 >>> print p.x 5.5 >>> print p.y 2.2 >>> print p.z AttributeError: Point instance has no attribute 'z' >>> type(p) <type '__main__'.Point'> >>> hasattr(p, 'x') True >>> hasattr(p, 'z') False Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
  • 328. hour 5: oops-a-daisy class If you try to access an attribute that doesn’t exist, you get an AttributeError If you are not sure what type an object is, you can use the type function If you are not sure whether an object has a particular attribute, you can use the built-in function hasattr >>> p = Point() >>> p.x = 5.5 >>> p.y = 2.2 >>> print p.x 5.5 >>> print p.y 2.2 >>> print p.z AttributeError: Point instance has no attribute 'z' >>> type(p) <type '__main__'.Point'> >>> hasattr(p, 'x') True >>> hasattr(p, 'z') False Satyaki Sikdar© Programming in Python April 22 2016 104 / 137
  • 329. hour 5: oops-a-daisy manipulating objects Dot notations are powerful. They can be used in any context >>> print '(%g, %g)' % (blank.x, blank.y) (3.0, 4.0) >>> import math >>> print math.sqrt(blank.x ** 2 + blank.y ** 2) 5.0 You can pass an instance as an argument in the usual way def print_point(p): print '(%g, %g)' % (p.x, p.y) print_point takes a Point as an arg and prints it in mathematical notation. To invoke it, you pass blank as an arg >>> print_point(blank) (3.0, 4.0) Inside the function, p is an alias for blank, so if the function modifies p, blank changes Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
  • 330. hour 5: oops-a-daisy manipulating objects Dot notations are powerful. They can be used in any context >>> print '(%g, %g)' % (blank.x, blank.y) (3.0, 4.0) >>> import math >>> print math.sqrt(blank.x ** 2 + blank.y ** 2) 5.0 You can pass an instance as an argument in the usual way def print_point(p): print '(%g, %g)' % (p.x, p.y) print_point takes a Point as an arg and prints it in mathematical notation. To invoke it, you pass blank as an arg >>> print_point(blank) (3.0, 4.0) Inside the function, p is an alias for blank, so if the function modifies p, blank changes Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
  • 331. hour 5: oops-a-daisy manipulating objects Dot notations are powerful. They can be used in any context >>> print '(%g, %g)' % (blank.x, blank.y) (3.0, 4.0) >>> import math >>> print math.sqrt(blank.x ** 2 + blank.y ** 2) 5.0 You can pass an instance as an argument in the usual way def print_point(p): print '(%g, %g)' % (p.x, p.y) print_point takes a Point as an arg and prints it in mathematical notation. To invoke it, you pass blank as an arg >>> print_point(blank) (3.0, 4.0) Inside the function, p is an alias for blank, so if the function modifies p, blank changes Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
  • 332. hour 5: oops-a-daisy manipulating objects Dot notations are powerful. They can be used in any context >>> print '(%g, %g)' % (blank.x, blank.y) (3.0, 4.0) >>> import math >>> print math.sqrt(blank.x ** 2 + blank.y ** 2) 5.0 You can pass an instance as an argument in the usual way def print_point(p): print '(%g, %g)' % (p.x, p.y) print_point takes a Point as an arg and prints it in mathematical notation. To invoke it, you pass blank as an arg >>> print_point(blank) (3.0, 4.0) Inside the function, p is an alias for blank, so if the function modifies p, blank changes Satyaki Sikdar© Programming in Python April 22 2016 105 / 137
  • 333. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 334. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 335. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 336. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 337. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 338. hour 5: oops-a-daisy manipulating objects def dist_bw_points(p1, p2): return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)) Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? There are at least two possibilities: specify one corner of the rectangle, the width, and the height specify two opposing corners Following the first one, here’s an example of the class definition. Corner represents the lower-left corner class Rectangle: '''Represents a rectangle. attributes: width, height, corner. ''' Satyaki Sikdar© Programming in Python April 22 2016 106 / 137
  • 339. hour 5: oops-a-daisy manipulating objects To represent a rectangle, you have to instantiate a Rectangle object and assign values to the attributes >>> box = Rectangle() >>> box.width = 100.0 >>> box.height = 200.0 >>> box.corner = Point() >>> box.corner.x = 0.0 >>> box.corner.y = 0.0 Figure: Object diagram for box The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x” Satyaki Sikdar© Programming in Python April 22 2016 107 / 137
  • 340. hour 5: oops-a-daisy manipulating objects To represent a rectangle, you have to instantiate a Rectangle object and assign values to the attributes >>> box = Rectangle() >>> box.width = 100.0 >>> box.height = 200.0 >>> box.corner = Point() >>> box.corner.x = 0.0 >>> box.corner.y = 0.0 Figure: Object diagram for box The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x” Satyaki Sikdar© Programming in Python April 22 2016 107 / 137
  • 341. hour 5: oops-a-daisy manipulating objects Functions can return instances find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle def find_center(rect): p = Point() p.x = rect.corner.x + rect.width / 2.0 p.y = rect.corner.y + rect.height / 2.0 return p >>> center = find_center(box) >>> print_point(center) (50.0, 100.0) Satyaki Sikdar© Programming in Python April 22 2016 108 / 137
  • 342. hour 5: oops-a-daisy manipulating objects Functions can return instances find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle def find_center(rect): p = Point() p.x = rect.corner.x + rect.width / 2.0 p.y = rect.corner.y + rect.height / 2.0 return p >>> center = find_center(box) >>> print_point(center) (50.0, 100.0) Satyaki Sikdar© Programming in Python April 22 2016 108 / 137
  • 343. hour 5: oops-a-daisy manipulating objects You can change the state of an object by making an assignment to one of its attributes You can also write functions that modify objects def grow_rectangle(rect, dwidth, dheight): rect.width += dwidth rect.height += dheight >>> print box.width 100.0 >>> print box.height 200.0 >>> grow_rectangle(box, 50, 100) >>> print box.width 150.0 >>> print box.height 300.0 Satyaki Sikdar© Programming in Python April 22 2016 109 / 137
  • 344. hour 5: oops-a-daisy manipulating objects You can change the state of an object by making an assignment to one of its attributes You can also write functions that modify objects def grow_rectangle(rect, dwidth, dheight): rect.width += dwidth rect.height += dheight >>> print box.width 100.0 >>> print box.height 200.0 >>> grow_rectangle(box, 50, 100) >>> print box.width 150.0 >>> print box.height 300.0 Satyaki Sikdar© Programming in Python April 22 2016 109 / 137
  • 345. hour 5: oops-a-daisy manipulating objects So far, the classes have been a little boring with just the definition and a docstring. Can we do more? Let’s find ou class Point: '''Represents a point in 2-D space.''' def print_point(p): print '(%g, %g)' % (p.x, p.y) >>> pt = Point() >>> pt.x = 3.5 >>> pt.y = 0 >>> Point.print_point(pt) #less common (3.5, 0) >>> pt.print_point() #widely used (3.5, 0) class Point: '''Represents a point in 2-D space.' def print_point( self ): print '(%g, %g)'%(self.x, self.y >>> pt = Point() >>> pt.x = 3.5 >>> pt.y = 0 >>> Point.print_point(pt) #less common (3.5, 0) >>> pt.print_point() #widely used (3.5, 0) By convention, the first arg of every function in a class is set to self Satyaki Sikdar© Programming in Python April 22 2016 110 / 137
  • 346. hour 5: oops-a-daisy manipulating objects So far, the classes have been a little boring with just the definition and a docstring. Can we do more? Let’s find ou class Point: '''Represents a point in 2-D space.''' def print_point(p): print '(%g, %g)' % (p.x, p.y) >>> pt = Point() >>> pt.x = 3.5 >>> pt.y = 0 >>> Point.print_point(pt) #less common (3.5, 0) >>> pt.print_point() #widely used (3.5, 0) class Point: '''Represents a point in 2-D space.' def print_point( self ): print '(%g, %g)'%(self.x, self.y >>> pt = Point() >>> pt.x = 3.5 >>> pt.y = 0 >>> Point.print_point(pt) #less common (3.5, 0) >>> pt.print_point() #widely used (3.5, 0) By convention, the first arg of every function in a class is set to self Satyaki Sikdar© Programming in Python April 22 2016 110 / 137
  • 347. hour 5: oops-a-daisy manipulating objects There’s no upper bound of the number of functions inside a class The first argument self is implicit, for example class Point: '''Represents a point in 2-D space.''' def print_point( self ): print '(%g, %g)'%(self.x, self.y) def transl(self, dx, dy): self.x += dx self.y += dy >>> pt = Point() >>> pt.transl(10, 20) #fine >>> pt.x = 6.0 >>> pt.transl(10, 20, 30) #not fine >>> pt.y = 8.0 TypeError: transl() takes exactly 3 arguments (4 given) >>> pt.print_point() (6.0, 8.0) Satyaki Sikdar© Programming in Python April 22 2016 111 / 137
  • 348. hour 5: oops-a-daisy manipulating objects There’s no upper bound of the number of functions inside a class The first argument self is implicit, for example class Point: '''Represents a point in 2-D space.''' def print_point( self ): print '(%g, %g)'%(self.x, self.y) def transl(self, dx, dy): self.x += dx self.y += dy >>> pt = Point() >>> pt.transl(10, 20) #fine >>> pt.x = 6.0 >>> pt.transl(10, 20, 30) #not fine >>> pt.y = 8.0 TypeError: transl() takes exactly 3 arguments (4 given) >>> pt.print_point() (6.0, 8.0) Satyaki Sikdar© Programming in Python April 22 2016 111 / 137
  • 349. hour 5: oops-a-daisy special methods the init method The init method is a special method that gets invoked when an object is created The full name is __init__, two underbars followed by init followed by two more underbars The parameters for init usually have the same name as the attributes The parameters here, are optional #inside class Point def __init__(self, x=0.0, y=0.0): self.x = x self.y = y #outside the class >>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed >>> p1.print_point() >>> p2.print_point() (0.0, 0.0) (2, 3.4) Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
  • 350. hour 5: oops-a-daisy special methods the init method The init method is a special method that gets invoked when an object is created The full name is __init__, two underbars followed by init followed by two more underbars The parameters for init usually have the same name as the attributes The parameters here, are optional #inside class Point def __init__(self, x=0.0, y=0.0): self.x = x self.y = y #outside the class >>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed >>> p1.print_point() >>> p2.print_point() (0.0, 0.0) (2, 3.4) Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
  • 351. hour 5: oops-a-daisy special methods the init method The init method is a special method that gets invoked when an object is created The full name is __init__, two underbars followed by init followed by two more underbars The parameters for init usually have the same name as the attributes The parameters here, are optional #inside class Point def __init__(self, x=0.0, y=0.0): self.x = x self.y = y #outside the class >>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed >>> p1.print_point() >>> p2.print_point() (0.0, 0.0) (2, 3.4) Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
  • 352. hour 5: oops-a-daisy special methods the init method The init method is a special method that gets invoked when an object is created The full name is __init__, two underbars followed by init followed by two more underbars The parameters for init usually have the same name as the attributes The parameters here, are optional #inside class Point def __init__(self, x=0.0, y=0.0): self.x = x self.y = y #outside the class >>> p1 = Point() >>> p2 = Point(2, 3.4) #also allowed >>> p1.print_point() >>> p2.print_point() (0.0, 0.0) (2, 3.4) Satyaki Sikdar© Programming in Python April 22 2016 112 / 137
  • 353. hour 5: oops-a-daisy special methods the str method __str__ is a special method like __init__ and it’s supposed to return a string representation of the object Takes just the object as the argument For the Point class, the str method can be like #inside the class Point def __str__(self): #allows you to use the print statement return '(%g, %g)' % (self.x, self.y) #outside the class >>> p = Point(2.0, 3.0) >>> print p (2.0, 3.0) Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
  • 354. hour 5: oops-a-daisy special methods the str method __str__ is a special method like __init__ and it’s supposed to return a string representation of the object Takes just the object as the argument For the Point class, the str method can be like #inside the class Point def __str__(self): #allows you to use the print statement return '(%g, %g)' % (self.x, self.y) #outside the class >>> p = Point(2.0, 3.0) >>> print p (2.0, 3.0) Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
  • 355. hour 5: oops-a-daisy special methods the str method __str__ is a special method like __init__ and it’s supposed to return a string representation of the object Takes just the object as the argument For the Point class, the str method can be like #inside the class Point def __str__(self): #allows you to use the print statement return '(%g, %g)' % (self.x, self.y) #outside the class >>> p = Point(2.0, 3.0) >>> print p (2.0, 3.0) Satyaki Sikdar© Programming in Python April 22 2016 113 / 137
  • 356. hour 5: oops-a-daisy special methods the add method __add__ is a special method like __str__ and it overloads the ’+’ operator Takes two arguments, the caller object and another object. Returns a new object that’s the sum of the two objects For the Point class, the add method can be like #inside the class Point def __add__(self, other_pt): new_pt = Point() new_pt.x = self.x + other_pt.x new_pt.y = self.y + other_pt.y return new_pt #outside the class >>> p1 = Point(2.0, 3.0) >>> print p1 + p2 >>> p2 = Point(3.4, 8.2) (5.4, 11.2) Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
  • 357. hour 5: oops-a-daisy special methods the add method __add__ is a special method like __str__ and it overloads the ’+’ operator Takes two arguments, the caller object and another object. Returns a new object that’s the sum of the two objects For the Point class, the add method can be like #inside the class Point def __add__(self, other_pt): new_pt = Point() new_pt.x = self.x + other_pt.x new_pt.y = self.y + other_pt.y return new_pt #outside the class >>> p1 = Point(2.0, 3.0) >>> print p1 + p2 >>> p2 = Point(3.4, 8.2) (5.4, 11.2) Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
  • 358. hour 5: oops-a-daisy special methods the add method __add__ is a special method like __str__ and it overloads the ’+’ operator Takes two arguments, the caller object and another object. Returns a new object that’s the sum of the two objects For the Point class, the add method can be like #inside the class Point def __add__(self, other_pt): new_pt = Point() new_pt.x = self.x + other_pt.x new_pt.y = self.y + other_pt.y return new_pt #outside the class >>> p1 = Point(2.0, 3.0) >>> print p1 + p2 >>> p2 = Point(3.4, 8.2) (5.4, 11.2) Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
  • 359. hour 5: oops-a-daisy special methods the add method __add__ is a special method like __str__ and it overloads the ’+’ operator Takes two arguments, the caller object and another object. Returns a new object that’s the sum of the two objects For the Point class, the add method can be like #inside the class Point def __add__(self, other_pt): new_pt = Point() new_pt.x = self.x + other_pt.x new_pt.y = self.y + other_pt.y return new_pt #outside the class >>> p1 = Point(2.0, 3.0) >>> print p1 + p2 >>> p2 = Point(3.4, 8.2) (5.4, 11.2) Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137
  • 360. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 361. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 362. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 363. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 364. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 365. hour 5: oops-a-daisy an elaborate example another example There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ for ranks. We’ll have trouble comparing the cards We use integers to encode the ranks and suits Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0 Ace → 1, Jack → 11, Queen → 12 and King → 13 Satyaki Sikdar© Programming in Python April 22 2016 115 / 137
  • 366. hour 5: oops-a-daisy an elaborate example the class definition class Card: '''Represents a standard playing card''' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank def __str__(self): return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) >>> two_of_clubs = Card() >>> queen_of_diamonds = Card(1, 12) Satyaki Sikdar© Programming in Python April 22 2016 116 / 137
  • 367. hour 5: oops-a-daisy an elaborate example class and instance attributes class attribute instance attribute Defined outside any method Defined inside methods Referred by class.class_attr Referred by inst.inst_attr One copy per class One copy per instance Eg: suit_names and rank_names Eg: suit and rank Figure: Class and instance attributes Satyaki Sikdar© Programming in Python April 22 2016 117 / 137
  • 368. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 369. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 370. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 371. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 372. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 373. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 374. hour 5: oops-a-daisy an elaborate example comparing cards For built-in types, there are relational operators (<, >, ==, etc.) that compare two things to produce a boolean For user-defined types, we need to override the __cmp__ method. It takes in two parameters, self and other, returns a positive number if the first object is greater a negative number if the second object is greater zero if they are equal The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit We arbitrarily choose that suit is more important, so all the Spades outrank all the Diamonds and so on. Satyaki Sikdar© Programming in Python April 22 2016 118 / 137
  • 375. hour 5: oops-a-daisy an elaborate example writing the __cmp__ method #inside Card class def __cmp__(self, other): if self.suit > other.suit: #check the suits return 1 elif self.suit < other.suit: return -1 elif self.rank > other.rank: #check the ranks return 1 elif self.rank < other.rank: return -1 else: #both the suits and the ranks are the same return 0 Satyaki Sikdar© Programming in Python April 22 2016 119 / 137
  • 376. hour 5: oops-a-daisy an elaborate example decks Now that we have Cards, we define Decks. It will contain a list of Cards The init method creates the entire deck of 52 cards class Deck: '''Represents a deck of cards''' def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) Satyaki Sikdar© Programming in Python April 22 2016 120 / 137
  • 377. hour 5: oops-a-daisy an elaborate example decks Now that we have Cards, we define Decks. It will contain a list of Cards The init method creates the entire deck of 52 cards class Deck: '''Represents a deck of cards''' def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) Satyaki Sikdar© Programming in Python April 22 2016 120 / 137
  • 378. hour 5: oops-a-daisy an elaborate example decks #inside class Deck def __str__(self): res = [] for card in self.cards: res.append(str(card)) return 'n'.join(res) def shuffle(self): random.shuffle(self.cards) #inside class Deck def pop_card(self): return self.cards.pop() def add_card(self, card): self.cards.append(card) def sort(self): self.cards.sort() >>> deck = Deck() >>> print deck.pop_card() King of Spades Satyaki Sikdar© Programming in Python April 22 2016 121 / 137
  • 379. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 380. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 381. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 382. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 383. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 384. hour 5: oops-a-daisy inheritance inheritance The language feature most often associated with object-oriented programming is inheritance It’s the ability to define a new class that’s a modified version of an existing class The existing class is called the parent and the new class is called the child We want a class to represent a hand that is, the set of cards held by a player A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards A hand is also different from a deck; there are operations we want for hands that don’t make sense for a deck Satyaki Sikdar© Programming in Python April 22 2016 122 / 137
  • 385. hour 5: oops-a-daisy inheritance The definition of a child class is like other class definitions, but the name of the parent class appears in parentheses class Hand(Deck): '''Represents a hand of playing cards''' This definition indicates that Hand inherits from Deck; that means we can use methods like pop_card and add_card for Hands as well as Decks Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init method for Hands should initialize cards with an empty list We can provide an init method, overriding the one in Deck #inside class Hand def __init__(self, label=''): self.cards = [] self.label = label Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
  • 386. hour 5: oops-a-daisy inheritance The definition of a child class is like other class definitions, but the name of the parent class appears in parentheses class Hand(Deck): '''Represents a hand of playing cards''' This definition indicates that Hand inherits from Deck; that means we can use methods like pop_card and add_card for Hands as well as Decks Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init method for Hands should initialize cards with an empty list We can provide an init method, overriding the one in Deck #inside class Hand def __init__(self, label=''): self.cards = [] self.label = label Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
  • 387. hour 5: oops-a-daisy inheritance The definition of a child class is like other class definitions, but the name of the parent class appears in parentheses class Hand(Deck): '''Represents a hand of playing cards''' This definition indicates that Hand inherits from Deck; that means we can use methods like pop_card and add_card for Hands as well as Decks Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init method for Hands should initialize cards with an empty list We can provide an init method, overriding the one in Deck #inside class Hand def __init__(self, label=''): self.cards = [] self.label = label Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
  • 388. hour 5: oops-a-daisy inheritance The definition of a child class is like other class definitions, but the name of the parent class appears in parentheses class Hand(Deck): '''Represents a hand of playing cards''' This definition indicates that Hand inherits from Deck; that means we can use methods like pop_card and add_card for Hands as well as Decks Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the init method for Hands should initialize cards with an empty list We can provide an init method, overriding the one in Deck #inside class Hand def __init__(self, label=''): self.cards = [] self.label = label Satyaki Sikdar© Programming in Python April 22 2016 123 / 137
  • 389. hour 5: oops-a-daisy inheritance So when you create a Hand, Python invokes it’s own init >>> hand = Hand('new hand') >>> print hand.cards [] >>> print hand.label new hand But the other methods are inherited from Deck >>> deck = Deck() >>> card = deck.pop_card() >>> hand.add_card(card) #add_card from Hand >>> print hand #using the str of Hand King of Spades A natural next step is to encapsulate this code in a method called move_cards #inside class Deck def move_cards(self, hand, card): for i in xrange(num): hand.add_card(self.pop_card()) move_cards takes two arguments, a Hand object and the number of cards to deal. Modifies both self and hand Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
  • 390. hour 5: oops-a-daisy inheritance So when you create a Hand, Python invokes it’s own init >>> hand = Hand('new hand') >>> print hand.cards [] >>> print hand.label new hand But the other methods are inherited from Deck >>> deck = Deck() >>> card = deck.pop_card() >>> hand.add_card(card) #add_card from Hand >>> print hand #using the str of Hand King of Spades A natural next step is to encapsulate this code in a method called move_cards #inside class Deck def move_cards(self, hand, card): for i in xrange(num): hand.add_card(self.pop_card()) move_cards takes two arguments, a Hand object and the number of cards to deal. Modifies both self and hand Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
  • 391. hour 5: oops-a-daisy inheritance So when you create a Hand, Python invokes it’s own init >>> hand = Hand('new hand') >>> print hand.cards [] >>> print hand.label new hand But the other methods are inherited from Deck >>> deck = Deck() >>> card = deck.pop_card() >>> hand.add_card(card) #add_card from Hand >>> print hand #using the str of Hand King of Spades A natural next step is to encapsulate this code in a method called move_cards #inside class Deck def move_cards(self, hand, card): for i in xrange(num): hand.add_card(self.pop_card()) move_cards takes two arguments, a Hand object and the number of cards to deal. Modifies both self and hand Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
  • 392. hour 5: oops-a-daisy inheritance So when you create a Hand, Python invokes it’s own init >>> hand = Hand('new hand') >>> print hand.cards [] >>> print hand.label new hand But the other methods are inherited from Deck >>> deck = Deck() >>> card = deck.pop_card() >>> hand.add_card(card) #add_card from Hand >>> print hand #using the str of Hand King of Spades A natural next step is to encapsulate this code in a method called move_cards #inside class Deck def move_cards(self, hand, card): for i in xrange(num): hand.add_card(self.pop_card()) move_cards takes two arguments, a Hand object and the number of cards to deal. Modifies both self and hand Satyaki Sikdar© Programming in Python April 22 2016 124 / 137
  • 393. hour 5: oops-a-daisy inheritance #inside class Deck def deal_hands(self, num_hands, cards_per_hand): hands = [] self.shuffle() #shuffling the deck for i in range(num_hands): hand = Hand('player %d' % (i)) for j in range(cards_per_hand): hand.add_card(self.pop_card()) hands.append(hand) return hands Now you have a proper framework for a card game, be it poker, blackjack or bridge! Satyaki Sikdar© Programming in Python April 22 2016 125 / 137
  • 394. hour 5: oops-a-daisy file handling 101 the need for file handling Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); if they shut down and restart, they pick up where they left off Big input and output sizes - too big for the main memory Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
  • 395. hour 5: oops-a-daisy file handling 101 the need for file handling Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); if they shut down and restart, they pick up where they left off Big input and output sizes - too big for the main memory Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
  • 396. hour 5: oops-a-daisy file handling 101 the need for file handling Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); if they shut down and restart, they pick up where they left off Big input and output sizes - too big for the main memory Satyaki Sikdar© Programming in Python April 22 2016 126 / 137
  • 397. hour 5: oops-a-daisy file handling 101 Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network. One of the simplest ways for programs to maintain their data is by reading and writing text files. fp_read = open('input.txt', 'r') fp_write = open('output.txt', 'w') Satyaki Sikdar© Programming in Python April 22 2016 127 / 137
  • 398. hour 5: oops-a-daisy file handling 101 Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network. One of the simplest ways for programs to maintain their data is by reading and writing text files. fp_read = open('input.txt', 'r') fp_write = open('output.txt', 'w') Satyaki Sikdar© Programming in Python April 22 2016 127 / 137
  • 399. hour 5: oops-a-daisy file handling 101 reading from files The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file >>> fin = open('input.txt', 'r') >>> print fin >>> <open file 'input.txt', mode 'r' at 0xb7eb2410> A few things to note: The file opened must exist. An IOError is thrown otherwise. The exact path to the file must be provided which includes the correct filename with extension (if any) Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
  • 400. hour 5: oops-a-daisy file handling 101 reading from files The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file >>> fin = open('input.txt', 'r') >>> print fin >>> <open file 'input.txt', mode 'r' at 0xb7eb2410> A few things to note: The file opened must exist. An IOError is thrown otherwise. The exact path to the file must be provided which includes the correct filename with extension (if any) Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
  • 401. hour 5: oops-a-daisy file handling 101 reading from files The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file >>> fin = open('input.txt', 'r') >>> print fin >>> <open file 'input.txt', mode 'r' at 0xb7eb2410> A few things to note: The file opened must exist. An IOError is thrown otherwise. The exact path to the file must be provided which includes the correct filename with extension (if any) Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
  • 402. hour 5: oops-a-daisy file handling 101 reading from files The built-in function open takes the name of the file as a parameter and returns a file object you can use to read the file >>> fin = open('input.txt', 'r') >>> print fin >>> <open file 'input.txt', mode 'r' at 0xb7eb2410> A few things to note: The file opened must exist. An IOError is thrown otherwise. The exact path to the file must be provided which includes the correct filename with extension (if any) Satyaki Sikdar© Programming in Python April 22 2016 128 / 137
  • 403. hour 5: oops-a-daisy file handling 101 reading files The file object provides several methods for reading, including readline, which reads characters from the file until it gets to a newline and returns the result as a string: >>> fin.readline() 'the first line n' If you keep on doing fin.readlines(), you’d end up reading the whole file, one line at a time. Let’s see a few examples of reading files. Satyaki Sikdar© Programming in Python April 22 2016 129 / 137
  • 404. hour 5: oops-a-daisy file handling 101 writing to files >>> fout = open('output.txt', 'w') >>> print fout <open file 'output.txt', mode 'w' at 0xb7eb2410> If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created >>> line1 = 'He left yesterday behind him, you might say he was born again, >>> fout.write(line1) Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end >>> line2 = 'you might say he found a key for every door.n' >>> fout.write(line2) Satyaki Sikdar© Programming in Python April 22 2016 130 / 137
  • 405. hour 5: oops-a-daisy file handling 101 using files for something meaningful Let’s combine the knowledge of file handling with dictionaries to do some basic lexical analysis import string def char_freq(filename): counter = dict() with open(filename, 'r') as f: raw_text = f.read() for c in raw_text: c = c.lower() if c in string.ascii_lowercase: if c in counter: counter[c] += 1 else: counter[c] = 1 return counter def normalize(counter): sum_values = float(sum(counter.values())) for key in counter: counter[key] /= sum_values return counter Satyaki Sikdar© Programming in Python April 22 2016 131 / 137
  • 406. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 407. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 408. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 409. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 410. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 411. hour 5: oops-a-daisy algorithms in Python algorithm design in Python One of the strong points of Python is the ease of expression Turning pseudocode into actual code is not difficult Let’s try to implement the Merge Sort algorithm in Python A high level idea of the algorithm Divide: Divide the n-element sequence into two subsequences of n 2 elements Conquer: Sort the subsequences recursively Combine: Merge the two sorted subsequences to produce the sorted answer Satyaki Sikdar© Programming in Python April 22 2016 132 / 137
  • 412. hour 5: oops-a-daisy the pseudocode Algorithm 1: MERGE(left, right) begin Append ∞ to left and right i ← 0, j ← 0 merged ← new list while len(merged) < len(left) + len(right) do if left[i] < right[j] then merged.append(left[i]) i ← i + 1 else merged.append(right[j]) j ← j + 1 return merged Algorithm 2: MERGE-SORT(A) begin if len(A) < 2 then return A else left ← first n 2 elements of A right ← last n 2 elements of A left ← MERGE − SORT(left) right ← MERGE − SORT(right) return MERGE(left, right) Satyaki Sikdar© Programming in Python April 22 2016 133 / 137
  • 413. hour 5: oops-a-daisy the pseudocode the core idea The algorithm is naturally recursive The MERGE method takes two sorted lists and merges into a single sorted list MERGE − SORT sorts the list recursively by breaking it into equal sized halves and sorting them A list having less than 2 elements is trivially sorted - base case Smaller sorted lists are agglomerated to form the overall sorted list Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
  • 414. hour 5: oops-a-daisy the pseudocode the core idea The algorithm is naturally recursive The MERGE method takes two sorted lists and merges into a single sorted list MERGE − SORT sorts the list recursively by breaking it into equal sized halves and sorting them A list having less than 2 elements is trivially sorted - base case Smaller sorted lists are agglomerated to form the overall sorted list Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
  • 415. hour 5: oops-a-daisy the pseudocode the core idea The algorithm is naturally recursive The MERGE method takes two sorted lists and merges into a single sorted list MERGE − SORT sorts the list recursively by breaking it into equal sized halves and sorting them A list having less than 2 elements is trivially sorted - base case Smaller sorted lists are agglomerated to form the overall sorted list Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
  • 416. hour 5: oops-a-daisy the pseudocode the core idea The algorithm is naturally recursive The MERGE method takes two sorted lists and merges into a single sorted list MERGE − SORT sorts the list recursively by breaking it into equal sized halves and sorting them A list having less than 2 elements is trivially sorted - base case Smaller sorted lists are agglomerated to form the overall sorted list Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
  • 417. hour 5: oops-a-daisy the pseudocode the core idea The algorithm is naturally recursive The MERGE method takes two sorted lists and merges into a single sorted list MERGE − SORT sorts the list recursively by breaking it into equal sized halves and sorting them A list having less than 2 elements is trivially sorted - base case Smaller sorted lists are agglomerated to form the overall sorted list Satyaki Sikdar© Programming in Python April 22 2016 134 / 137
  • 418. hour 5: oops-a-daisy implementation Algorithm 3: MERGE(left, right) begin Append ∞ to left and right i ← 0, j ← 0 merged ← new list while len(merged) < len(left) + len(right) do if left[i] < right[j] then merged.append(left[i]) i ← i + 1 else merged.append(right[j]) j ← j + 1 return merged def merge(left, right): left.append(float('inf')) right.append(float('inf')) i = 0 j = 0 merged = [] while len(merged) < len(left) + len(right): if left[i] < right[j]: merged.append(left[i]) i += 1 else: merged.append(right[j]) j += 1 return merged Satyaki Sikdar© Programming in Python April 22 2016 135 / 137
  • 419. hour 5: oops-a-daisy implementation Algorithm 4: MERGE-SORT(A) begin if len(A) < 2 then return A else left ← first n 2 elements of A right ← last n 2 elements of A left ← MERGE − SORT(left) right ← MERGE − SORT(right) return MERGE(left, right) def merge_sort(A): if len(A) < 2: return A else: mid = len(A) / 2 left = A[: mid] right = A[mid: ] left = merge_sort(left) right = merge_sort(right) return merge(left, right) Satyaki Sikdar© Programming in Python April 22 2016 136 / 137
  • 420. hour 5: oops-a-daisy implementation That’s all for today! Hope you had fun! Make sure you have a working networkx setup for tomorrow... Satyaki Sikdar© Programming in Python April 22 2016 137 / 137