420
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

A 12 hour workshop on Introduction to Python

Embed Size (px)

Citation preview

Page 1: A 12 hour workshop on Introduction to Python

Programming in PythonA Two Day Workshop

Satyaki Sikdar

Vice ChairACM Student Chapter

Heritage Institute of Technology

April 22 2016

Satyaki Sikdar© Programming in Python April 22 2016 1 / 137

Page 2: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 3: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 4: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 5: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 6: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 7: A 12 hour workshop on Introduction to Python

hour 0: intro whoami

whoami

I Extremely lazyI Coding in Python since the summer of 2013 - not an expert by any meansI An average programmer at best. Comfortable writing 750 - 1000 lines of code

I In terms of difficulty levels in FIFA, I’m stuck somewhere midway between semi-pro andprofessional

I I love Python - duh!I 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

Page 8: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 9: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 10: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 11: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 12: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 13: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 14: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 15: A 12 hour workshop on Introduction to Python

hour 0: intro expectations and takeaways

great expectations

Things you can expect from meI ClarityI No spoon feedingI Desperate attempts at making jokes

Things I expect from you

I An open mindI Patience - not everything would make perfect sense at firstI Attention - especially to detailsI Cooperation - it’s going to be a long haulI Interruptions - feel free to stop me to ask relevant questions

Satyaki Sikdar© Programming in Python April 22 2016 3 / 137

Page 16: A 12 hour workshop on Introduction to Python

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 certainway

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

Page 17: A 12 hour workshop on Introduction to Python

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 certainway

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

Page 18: A 12 hour workshop on Introduction to Python

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 certainway

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

Page 19: A 12 hour workshop on Introduction to Python

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 certainway

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

Page 20: A 12 hour workshop on Introduction to Python

hour 0: intro lesson plan

the lesson plan for day I

hour topic1 introduction, motivation, Guido, awesomeness of Python2 playing around with the interpreter - variables, simple data types3 predefined functions, conditionals, lists, loops4 tuples, user defined functions, basic recursion5 sets, dictionaries, errors and exceptions, intro to OOP6 OOP - inheritance, applying OOP

Satyaki Sikdar© Programming in Python April 22 2016 5 / 137

Page 21: A 12 hour workshop on Introduction to Python

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

I Born: 31 January, 1956 in Haarlem, The Netherlands

I Studied Computer Science from the University of Amsterdam

I Started Python as a hobby project in 1989. It grew into anew language in a couple of years.

I Recognized as a Distinguished Engineer by ACM

I Xoogler and now works for Dropbox

Satyaki Sikdar© Programming in Python April 22 2016 6 / 137

Page 22: A 12 hour workshop on Introduction to Python

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

I Born: 31 January, 1956 in Haarlem, The Netherlands

I Studied Computer Science from the University of Amsterdam

I Started Python as a hobby project in 1989. It grew into anew language in a couple of years.

I Recognized as a Distinguished Engineer by ACM

I Xoogler and now works for Dropbox

Satyaki Sikdar© Programming in Python April 22 2016 6 / 137

Page 23: A 12 hour workshop on Introduction to Python

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

I Born: 31 January, 1956 in Haarlem, The Netherlands

I Studied Computer Science from the University of Amsterdam

I Started Python as a hobby project in 1989. It grew into anew language in a couple of years.

I Recognized as a Distinguished Engineer by ACM

I Xoogler and now works for Dropbox

Satyaki Sikdar© Programming in Python April 22 2016 6 / 137

Page 24: A 12 hour workshop on Introduction to Python

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

I Born: 31 January, 1956 in Haarlem, The Netherlands

I Studied Computer Science from the University of Amsterdam

I Started Python as a hobby project in 1989. It grew into anew language in a couple of years.

I Recognized as a Distinguished Engineer by ACM

I Xoogler and now works for Dropbox

Satyaki Sikdar© Programming in Python April 22 2016 6 / 137

Page 25: A 12 hour workshop on Introduction to Python

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

I Born: 31 January, 1956 in Haarlem, The Netherlands

I Studied Computer Science from the University of Amsterdam

I Started Python as a hobby project in 1989. It grew into anew language in a couple of years.

I Recognized as a Distinguished Engineer by ACM

I Xoogler and now works for Dropbox

Satyaki Sikdar© Programming in Python April 22 2016 6 / 137

Page 26: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

it’s good to be popular

I It’s true for people and programming languages alike

I Tons of resources to get help from if you are stuck

I You’ll get a lot of people to collaborate

I Employment opportunities open up

Satyaki Sikdar© Programming in Python April 22 2016 7 / 137

Page 27: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

it’s good to be popular

I It’s true for people and programming languages alike

I Tons of resources to get help from if you are stuck

I You’ll get a lot of people to collaborate

I Employment opportunities open up

Satyaki Sikdar© Programming in Python April 22 2016 7 / 137

Page 28: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

it’s good to be popular

I It’s true for people and programming languages alike

I Tons of resources to get help from if you are stuck

I You’ll get a lot of people to collaborate

I Employment opportunities open up

Satyaki Sikdar© Programming in Python April 22 2016 7 / 137

Page 29: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

it’s good to be popular

I It’s true for people and programming languages alike

I Tons of resources to get help from if you are stuck

I You’ll get a lot of people to collaborate

I Employment opportunities open up

Satyaki Sikdar© Programming in Python April 22 2016 7 / 137

Page 30: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

popularity of Python©codeeval - hiring demand trends

Satyaki Sikdar© Programming in Python April 22 2016 8 / 137

Page 31: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

popularity of Python©PYPL

Satyaki Sikdar© Programming in Python April 22 2016 9 / 137

Page 32: A 12 hour workshop on Introduction to Python

hour 0: intro popularity

popularity of Python

Satyaki Sikdar© Programming in Python April 22 2016 10 / 137

Page 33: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 34: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 35: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 36: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 37: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 38: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 39: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

what makes Py Awesome?

I Open source license - right from the early days

I Very versatile

I The Zen of Python - you should read it every now and then

I A strong and active community

I PyPI - the modules repository has over 30, 000 user created modules for ready use

I Killer apps like Django and Pandas

I Lots and lots of reference materials available including books, video lectures and tutorials

Satyaki Sikdar© Programming in Python April 22 2016 11 / 137

Page 40: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

the awesomeness continues!

I Ease of learning - you’ll see it soon

I Very teachable - low syntax overhead

I Rapid development cycle - easy to express yourself

I Readable, beautiful and brevity - you’ll love to code

I Interactive prompt

Satyaki Sikdar© Programming in Python April 22 2016 12 / 137

Page 41: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

the awesomeness continues!

I Ease of learning - you’ll see it soon

I Very teachable - low syntax overhead

I Rapid development cycle - easy to express yourself

I Readable, beautiful and brevity - you’ll love to code

I Interactive prompt

Satyaki Sikdar© Programming in Python April 22 2016 12 / 137

Page 42: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

the awesomeness continues!

I Ease of learning - you’ll see it soon

I Very teachable - low syntax overhead

I Rapid development cycle - easy to express yourself

I Readable, beautiful and brevity - you’ll love to code

I Interactive prompt

Satyaki Sikdar© Programming in Python April 22 2016 12 / 137

Page 43: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

the awesomeness continues!

I Ease of learning - you’ll see it soon

I Very teachable - low syntax overhead

I Rapid development cycle - easy to express yourself

I Readable, beautiful and brevity - you’ll love to code

I Interactive prompt

Satyaki Sikdar© Programming in Python April 22 2016 12 / 137

Page 44: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

the awesomeness continues!

I Ease of learning - you’ll see it soon

I Very teachable - low syntax overhead

I Rapid development cycle - easy to express yourself

I Readable, beautiful and brevity - you’ll love to code

I Interactive prompt

Satyaki Sikdar© Programming in Python April 22 2016 12 / 137

Page 45: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

©xkcd.comSatyaki Sikdar© Programming in Python April 22 2016 13 / 137

Page 46: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

places were Py is used

I From supercomputers to Instagram, from labs to financialfirms

I You can do machine learning, NLP to building web pages andwrangling social networks

I Really hip among startups

I Schools like M.I.T., Rice, Stanford, Havard have switched toPython for their programming courses in the CS curriculum

Satyaki Sikdar© Programming in Python April 22 2016 14 / 137

Page 47: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

places were Py is used

I From supercomputers to Instagram, from labs to financialfirms

I You can do machine learning, NLP to building web pages andwrangling social networks

I Really hip among startups

I Schools like M.I.T., Rice, Stanford, Havard have switched toPython for their programming courses in the CS curriculum

Satyaki Sikdar© Programming in Python April 22 2016 14 / 137

Page 48: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

places were Py is used

I From supercomputers to Instagram, from labs to financialfirms

I You can do machine learning, NLP to building web pages andwrangling social networks

I Really hip among startups

I Schools like M.I.T., Rice, Stanford, Havard have switched toPython for their programming courses in the CS curriculum

Satyaki Sikdar© Programming in Python April 22 2016 14 / 137

Page 49: A 12 hour workshop on Introduction to Python

hour 0: intro awesomeness of Python

places were Py is used

I From supercomputers to Instagram, from labs to financialfirms

I You can do machine learning, NLP to building web pages andwrangling social networks

I Really hip among startups

I Schools like M.I.T., Rice, Stanford, Havard have switched toPython for their programming courses in the CS curriculum

Satyaki Sikdar© Programming in Python April 22 2016 14 / 137

Page 50: A 12 hour workshop on Introduction to Python

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 - 1while 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

Page 51: A 12 hour workshop on Introduction to Python

hour 0: intro indentation

indentation & Python

It’s absolutely essential to indent Python code.I It seems natural

I Braces? Yuck!!

I According to PEP8, you must indent every block of code by 4 spaces

I 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

Page 52: A 12 hour workshop on Introduction to Python

hour 0: intro indentation

indentation & Python

It’s absolutely essential to indent Python code.I It seems natural

I Braces? Yuck!!

I According to PEP8, you must indent every block of code by 4 spaces

I 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

Page 53: A 12 hour workshop on Introduction to Python

hour 0: intro indentation

indentation & Python

It’s absolutely essential to indent Python code.I It seems natural

I Braces? Yuck!!

I According to PEP8, you must indent every block of code by 4 spaces

I 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

Page 54: A 12 hour workshop on Introduction to Python

hour 0: intro indentation

indentation & Python

It’s absolutely essential to indent Python code.I It seems natural

I Braces? Yuck!!

I According to PEP8, you must indent every block of code by 4 spaces

I 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

Page 55: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

say hello to the interpreter!

I Python is an interpreted language. It executes codes line by line

I It has an interactive prompt with which you can play around without any fear

I The prompt looks like this >>>

I 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

Page 56: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

say hello to the interpreter!

I Python is an interpreted language. It executes codes line by line

I It has an interactive prompt with which you can play around without any fear

I The prompt looks like this >>>

I 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

Page 57: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

say hello to the interpreter!

I Python is an interpreted language. It executes codes line by line

I It has an interactive prompt with which you can play around without any fear

I The prompt looks like this >>>

I 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

Page 58: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

say hello to the interpreter!

I Python is an interpreted language. It executes codes line by line

I It has an interactive prompt with which you can play around without any fear

I The prompt looks like this >>>

I 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

Page 59: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

the print statement

I It’s one of the most used statements in PythonI Does what the name says, it prints stuffI It’s very smart - one statement to rule them all - works for every data type - no messy

loops needed

print 1 + 1 # >>> 2print 'joe root' # >>> joe root (notice the lack of quotes)print True # >>> Trueprint 'hello', 'world' # >>> hello world (notice the space)print 'hello'print 'world' #hello and world in separate linesprint 'hello',print 'world' #hello and world in the same line (notice the comma)

Satyaki Sikdar© Programming in Python April 22 2016 18 / 137

Page 60: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

the print statement

I It’s one of the most used statements in PythonI Does what the name says, it prints stuffI It’s very smart - one statement to rule them all - works for every data type - no messy

loops needed

print 1 + 1 # >>> 2print 'joe root' # >>> joe root (notice the lack of quotes)print True # >>> Trueprint 'hello', 'world' # >>> hello world (notice the space)print 'hello'print 'world' #hello and world in separate linesprint 'hello',print 'world' #hello and world in the same line (notice the comma)

Satyaki Sikdar© Programming in Python April 22 2016 18 / 137

Page 61: A 12 hour workshop on Introduction to Python

hour 1: Python 101 the interpreter and more ..

the print statement

I It’s one of the most used statements in PythonI Does what the name says, it prints stuffI It’s very smart - one statement to rule them all - works for every data type - no messy

loops needed

print 1 + 1 # >>> 2print 'joe root' # >>> joe root (notice the lack of quotes)print True # >>> Trueprint 'hello', 'world' # >>> hello world (notice the space)print 'hello'print 'world' #hello and world in separate linesprint 'hello',print 'world' #hello and world in the same line (notice the comma)

Satyaki Sikdar© Programming in Python April 22 2016 18 / 137

Page 62: A 12 hour workshop on Introduction to Python

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

Page 63: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 64: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 65: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 66: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 67: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 68: A 12 hour workshop on Introduction to Python

hour 1: Python 101 data types

data types in PythonThere 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. isa valid floating point number.

4 complex numbers (complex): Handles complex numbers. Eg: 1 + 2j is a valid complexnumber in Python.

5 strings (str): Handles strings, eg: ’jimmy anderson’ and "jimmy anderson" are both validstrings, but ’jimmy anderson" or "jimmy anderson’ is not.

6 booleans (bool): True and False

Satyaki Sikdar© Programming in Python April 22 2016 20 / 137

Page 69: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 70: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 71: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 72: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 73: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 74: A 12 hour workshop on Introduction to Python

hour 1: Python 101 integers

integers

Supports basic operations as it is expected to. Any of the things shouldn’t come as a surpriseto you.

I + for addition. Eg: 50 + 7 gives 57

I * for multiplication. Eg: 50 * 7 gives 350

I / for integer division. Eg: 50 / 7 gives 7 (why?)

I % for modulo operation. Eg: 50 % 7 gives 1

I ** for exponentiation. Eg: 2 ** 7 gives 128

I >>, <<, ˜ are also allowed

Parenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 21 / 137

Page 75: A 12 hour workshop on Introduction to Python

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 surpriseto you.

I + for addition. Eg: 50.2 + 7.4 gives 57.6

I * for multiplication. Eg: 50.2 * 5 gives 251.0

I / for division. Eg: 50.0 / 7 gives 7.1428

I % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999

I ** 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

Page 76: A 12 hour workshop on Introduction to Python

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 surpriseto you.

I + for addition. Eg: 50.2 + 7.4 gives 57.6

I * for multiplication. Eg: 50.2 * 5 gives 251.0

I / for division. Eg: 50.0 / 7 gives 7.1428

I % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999

I ** 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

Page 77: A 12 hour workshop on Introduction to Python

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 surpriseto you.

I + for addition. Eg: 50.2 + 7.4 gives 57.6

I * for multiplication. Eg: 50.2 * 5 gives 251.0

I / for division. Eg: 50.0 / 7 gives 7.1428

I % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999

I ** 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

Page 78: A 12 hour workshop on Introduction to Python

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 surpriseto you.

I + for addition. Eg: 50.2 + 7.4 gives 57.6

I * for multiplication. Eg: 50.2 * 5 gives 251.0

I / for division. Eg: 50.0 / 7 gives 7.1428

I % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999

I ** 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

Page 79: A 12 hour workshop on Introduction to Python

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 surpriseto you.

I + for addition. Eg: 50.2 + 7.4 gives 57.6

I * for multiplication. Eg: 50.2 * 5 gives 251.0

I / for division. Eg: 50.0 / 7 gives 7.1428

I % for modulo operation. Eg: 50.0 % 7.2 gives 6.79999

I ** 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

Page 80: A 12 hour workshop on Introduction to Python

hour 1: Python 101 complex numbers

complex numbers

Note: j is used in place of iI + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)

I * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)

I / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)

I % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)

I ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40jParenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 23 / 137

Page 81: A 12 hour workshop on Introduction to Python

hour 1: Python 101 complex numbers

complex numbers

Note: j is used in place of iI + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)

I * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)

I / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)

I % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)

I ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40jParenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 23 / 137

Page 82: A 12 hour workshop on Introduction to Python

hour 1: Python 101 complex numbers

complex numbers

Note: j is used in place of iI + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)

I * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)

I / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)

I % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)

I ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40jParenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 23 / 137

Page 83: A 12 hour workshop on Introduction to Python

hour 1: Python 101 complex numbers

complex numbers

Note: j is used in place of iI + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)

I * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)

I / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)

I % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)

I ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40jParenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 23 / 137

Page 84: A 12 hour workshop on Introduction to Python

hour 1: Python 101 complex numbers

complex numbers

Note: j is used in place of iI + for addition. Eg: (2 + 3j)+ (5 + 4j) gives (7 + 7j)

I * for multiplication. Eg: (2 + 3j) * (5 + 4j) gives (-2 + 23j)

I / for division. Eg: (5 + 4j) / (1 + 2j) gives (2.6 - 1.2j)

I % for modulo operation. Eg: (5 + 4j) % (1 + 3j) gives (4 + 1j)

I ** is for exponentiation. Eg: (5 + 4j) ** 2 gives 9 + 40jParenthization of expressions is allowed with the help of ()

Satyaki Sikdar© Programming in Python April 22 2016 23 / 137

Page 85: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

no strings attached!

I Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH

I Bigger strings consist of smaller strings. There’s no such thing as a character in Python.

I + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’and ’Cook’ + ’Alastair’ gives ’CookAlastair’

I * 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

Page 86: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

no strings attached!

I Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH

I Bigger strings consist of smaller strings. There’s no such thing as a character in Python.

I + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’and ’Cook’ + ’Alastair’ gives ’CookAlastair’

I * 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

Page 87: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

no strings attached!

I Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH

I Bigger strings consist of smaller strings. There’s no such thing as a character in Python.

I + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’and ’Cook’ + ’Alastair’ gives ’CookAlastair’

I * 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

Page 88: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

no strings attached!

I Can be enclosed within either single or double quotes. DO NOT MIX AND MATCH

I Bigger strings consist of smaller strings. There’s no such thing as a character in Python.

I + used for appending two strings together. Eg: ’Alastair’ + ’Cook’ gives ’AlastairCook’and ’Cook’ + ’Alastair’ gives ’CookAlastair’

I * 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

Page 89: A 12 hour workshop on Introduction to Python

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.I len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6

I 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 soon.

I 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

Page 90: A 12 hour workshop on Introduction to Python

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.I len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6

I 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 soon.

I 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

Page 91: A 12 hour workshop on Introduction to Python

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.I len(s) :- gives you the length of the string s. Eg: len(’broady’) = 6

I 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 soon.

I 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

Page 92: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

string methods - II

I s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s homefor imaginary friends’ .count (’fo’) = 2

I s.find(substring) :- gives you the index of the substring in the string. Eg:’Alastair’.find(’stair’) = 3

I s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’AlastairCook 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

Page 93: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

string methods - II

I s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s homefor imaginary friends’ .count (’fo’) = 2

I s.find(substring) :- gives you the index of the substring in the string. Eg:’Alastair’.find(’stair’) = 3

I s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’AlastairCook 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

Page 94: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

string methods - II

I s.count(substring) :- gives you the count of the substring in the string. Eg: ’foster’s homefor imaginary friends’ .count (’fo’) = 2

I s.find(substring) :- gives you the index of the substring in the string. Eg:’Alastair’.find(’stair’) = 3

I s.split(delim) :- Splits s using a delimiter delim. Returns a list of substrings. Eg: ’AlastairCook 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

Page 95: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

string slicing - revisited

I So far, we have sliced strings in a manner like st[start: end]

I You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaultsto 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 9for c in st[: : 2]:

print c, #output: 0 2 4 6 8for c in st[: : 3]:

print c, #output: 0 3 6 9for 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

Page 96: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

string slicing - revisited

I So far, we have sliced strings in a manner like st[start: end]

I You can use a third parameter stride as well! So it can be st[start: end: stride]. It defaultsto 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 9for c in st[: : 2]:

print c, #output: 0 2 4 6 8for c in st[: : 3]:

print c, #output: 0 3 6 9for 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

Page 97: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

palindrome checking

I A palindrome is a word, phrase, number, or other sequence of characters which reads thesame backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,Panama!’

I Often it’s allowed to skip over spaces and punctuation marks

I It’s a classic problem while dealing with strings. And we’ll stick to character-unitpalindromes. 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

Page 98: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

palindrome checking

I A palindrome is a word, phrase, number, or other sequence of characters which reads thesame backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,Panama!’

I Often it’s allowed to skip over spaces and punctuation marks

I It’s a classic problem while dealing with strings. And we’ll stick to character-unitpalindromes. 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

Page 99: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

palindrome checking

I A palindrome is a word, phrase, number, or other sequence of characters which reads thesame backward or forward. Examples: ’race car’, ’taco cat’, ’A man, a plan, a canal,Panama!’

I Often it’s allowed to skip over spaces and punctuation marks

I It’s a classic problem while dealing with strings. And we’ll stick to character-unitpalindromes. 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

Page 100: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

multi-line strings and escape characters

Multi-line stringsI Multi-line strings are different from ordinary strings. As the name suggests, they can span

over multiple lines

I Enclosed by a pair of ” ’ or """

I They support all the string operations - indexing, slicing and dicing...

I End of lines are marked with the EOL (\n) characterEscape characters

I \ 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

Page 101: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

multi-line strings and escape characters

Multi-line stringsI Multi-line strings are different from ordinary strings. As the name suggests, they can span

over multiple lines

I Enclosed by a pair of ” ’ or """

I They support all the string operations - indexing, slicing and dicing...

I End of lines are marked with the EOL (\n) characterEscape characters

I \ 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

Page 102: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

multi-line strings and escape characters

Multi-line stringsI Multi-line strings are different from ordinary strings. As the name suggests, they can span

over multiple lines

I Enclosed by a pair of ” ’ or """

I They support all the string operations - indexing, slicing and dicing...

I End of lines are marked with the EOL (\n) characterEscape characters

I \ 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

Page 103: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

multi-line strings and escape characters

Multi-line stringsI Multi-line strings are different from ordinary strings. As the name suggests, they can span

over multiple lines

I Enclosed by a pair of ” ’ or """

I They support all the string operations - indexing, slicing and dicing...

I End of lines are marked with the EOL (\n) characterEscape characters

I \ 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

Page 104: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

multi-line strings and escape characters

Multi-line stringsI Multi-line strings are different from ordinary strings. As the name suggests, they can span

over multiple lines

I Enclosed by a pair of ” ’ or """

I They support all the string operations - indexing, slicing and dicing...

I End of lines are marked with the EOL (\n) characterEscape characters

I \ 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

Page 105: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

the Boolean data type

They represent the logical True and False. The operations that they support are as follows:

I Negation: Using the word not before True or False negates it. >>> not True yields Falseand >>> not False yields True

I Logical and: The result is True if and only if every argument is True. In Python, use theword and

I Logical or: The result is False if and only if every argument is False. In Python, use theword or

Satyaki Sikdar© Programming in Python April 22 2016 30 / 137

Page 106: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

the Boolean data type

They represent the logical True and False. The operations that they support are as follows:

I Negation: Using the word not before True or False negates it. >>> not True yields Falseand >>> not False yields True

I Logical and: The result is True if and only if every argument is True. In Python, use theword and

I Logical or: The result is False if and only if every argument is False. In Python, use theword or

Satyaki Sikdar© Programming in Python April 22 2016 30 / 137

Page 107: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

the Boolean data type

They represent the logical True and False. The operations that they support are as follows:

I Negation: Using the word not before True or False negates it. >>> not True yields Falseand >>> not False yields True

I Logical and: The result is True if and only if every argument is True. In Python, use theword and

I Logical or: The result is False if and only if every argument is False. In Python, use theword or

Satyaki Sikdar© Programming in Python April 22 2016 30 / 137

Page 108: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

truth tables for logical and and logical or

A B A or B A and B

False False False FalseFalse True True FalseTrue False True FalseTrue True True True

Satyaki Sikdar© Programming in Python April 22 2016 31 / 137

Page 109: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 110: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 111: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 112: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 113: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 114: A 12 hour workshop on Introduction to Python

hour 1: Python 101 strings

logical comparisons

The comparisons yield either True or FalseI Equals (==): 2 == 3 is False

I Not equal (!=): 2 != 3 is True

I Greater than (>): 2 > 3 is False

I Lesser than (<): 2 < 3 is True

I Greater than or equal to (>=): 2 >= 4 is False

I Lesser than or equal to (<=): 2 <= 4 is True

Satyaki Sikdar© Programming in Python April 22 2016 32 / 137

Page 115: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 116: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 117: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 118: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 119: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 120: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

variables!

I Variables provide a way to associate names with objects

I I personally prefer under_bars over camelCase. It’s up to you to decide

I A variable is just a name. An object can have one, more than one or no names associatedwith it.

I Assignment statements are used to assign values to variables. a = 15

I Notice, there is no data types being mentioned! So you can do a = 15 and then a = ’bloo’and it’ll be alright!

I Note: julia, Julia, and JULIA are all different

Satyaki Sikdar© Programming in Python April 22 2016 33 / 137

Page 121: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

bindings

Consider the codepi = 3.14159radius = 11.2area = pi * (radius ** 2)radius = 14.3

Figure: Binding of variables to objects

Satyaki Sikdar© Programming in Python April 22 2016 34 / 137

Page 122: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

meaningful names!

a = 3.14159b = 11.2c = a * (b ** 2)

pi = 3.14159diameter = 11.2area = pi * (diameter ** 2)

I The two codes to Python are exactly the same

I To a human, they are pretty different! The code on the right is better, but there’s aproblem?!

I The variable should have been called radius instead of diameter, or the area formula iswrong!

Satyaki Sikdar© Programming in Python April 22 2016 35 / 137

Page 123: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

meaningful names!

a = 3.14159b = 11.2c = a * (b ** 2)

pi = 3.14159diameter = 11.2area = pi * (diameter ** 2)

I The two codes to Python are exactly the same

I To a human, they are pretty different! The code on the right is better, but there’s aproblem?!

I The variable should have been called radius instead of diameter, or the area formula iswrong!

Satyaki Sikdar© Programming in Python April 22 2016 35 / 137

Page 124: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

meaningful names!

a = 3.14159b = 11.2c = a * (b ** 2)

pi = 3.14159diameter = 11.2area = pi * (diameter ** 2)

I The two codes to Python are exactly the same

I To a human, they are pretty different! The code on the right is better, but there’s aproblem?!

I The variable should have been called radius instead of diameter, or the area formula iswrong!

Satyaki Sikdar© Programming in Python April 22 2016 35 / 137

Page 125: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

a comic from xkcd.com

Satyaki Sikdar© Programming in Python April 22 2016 36 / 137

Page 126: A 12 hour workshop on Introduction to Python

hour 1: Python 101 variables and bindings

the names which must not be given!

and as assertbreak class continuedef del elifelse except execfinally for fromglobal if importin is lambdanot or passprint raise returntry while with

yieldSatyaki Sikdar© Programming in Python April 22 2016 37 / 137

Page 127: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

taking input from the user!

name = raw_input('Enter something!')print name#example output: Edwinprint type(name)#example output: <type 'str'>

Satyaki Sikdar© Programming in Python April 22 2016 38 / 137

Page 128: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 129: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 130: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 131: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 132: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 133: A 12 hour workshop on Introduction to Python

hour 1: Python 101 basic i/o

I raw_input returns a string

I What if we need to take integer or float inputs? Typecast it! So int(’12’) gives the integer12

I float(’12.4’) gives 12.4 (a float)

I int(’12.4’) makes it 12 (an integer)

I float(12) makes it 12.0 (a float)

I Don’t overdo it! int(’tendo’) makes the interpreter go nuts! Raises ValueError

Satyaki Sikdar© Programming in Python April 22 2016 39 / 137

Page 134: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

Satyaki Sikdar© Programming in Python April 22 2016 40 / 137

Page 135: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

making decisions

I Making decisions are an integral part of our lives. Thus, it becomes essential for our codesto make decisions too!

I Python has if, else and elif to help your code make decisions

I The syntax is as followsif boolean_expression1:

do_somethingelif boolean_expression2:

do_something_differentelse:

do_something_else

Satyaki Sikdar© Programming in Python April 22 2016 41 / 137

Page 136: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

making decisions

I Making decisions are an integral part of our lives. Thus, it becomes essential for our codesto make decisions too!

I Python has if, else and elif to help your code make decisions

I The syntax is as followsif boolean_expression1:

do_somethingelif boolean_expression2:

do_something_differentelse:

do_something_else

Satyaki Sikdar© Programming in Python April 22 2016 41 / 137

Page 137: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

making decisions

I Making decisions are an integral part of our lives. Thus, it becomes essential for our codesto make decisions too!

I Python has if, else and elif to help your code make decisions

I The syntax is as followsif boolean_expression1:

do_somethingelif boolean_expression2:

do_something_differentelse:

do_something_else

Satyaki Sikdar© Programming in Python April 22 2016 41 / 137

Page 138: A 12 hour workshop on Introduction to Python

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

Page 139: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

a simple illustration IINested 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

Page 140: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

the in keyword

I The in keyword is used for containment checking

I Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ianbotham’ returns True, but ’beefy’ in ’sir ian botham’ returns False

I Thus in can be used in if, elif statements.

Satyaki Sikdar© Programming in Python April 22 2016 44 / 137

Page 141: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

the in keyword

I The in keyword is used for containment checking

I Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ianbotham’ returns True, but ’beefy’ in ’sir ian botham’ returns False

I Thus in can be used in if, elif statements.

Satyaki Sikdar© Programming in Python April 22 2016 44 / 137

Page 142: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats conditionals

the in keyword

I The in keyword is used for containment checking

I Returns a boolean. Can be used for substring check in strings. Eg: ’bot’ in ’sir ianbotham’ returns True, but ’beefy’ in ’sir ian botham’ returns False

I Thus in can be used in if, elif statements.

Satyaki Sikdar© Programming in Python April 22 2016 44 / 137

Page 143: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

loops: the basic idea

Satyaki Sikdar© Programming in Python April 22 2016 45 / 137

Page 144: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

say hello to while loops

I while loops in Python are no different than the while loops in other common languages.Phew!

I It’s similar to a conditional statement. But, no else blocks

I As long as the condition is valid, the loop body keeps executing. The condition isre-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 + xiters_left = iters_left - 1

>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137

Page 145: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

say hello to while loops

I while loops in Python are no different than the while loops in other common languages.Phew!

I It’s similar to a conditional statement. But, no else blocks

I As long as the condition is valid, the loop body keeps executing. The condition isre-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 + xiters_left = iters_left - 1

>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137

Page 146: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

say hello to while loops

I while loops in Python are no different than the while loops in other common languages.Phew!

I It’s similar to a conditional statement. But, no else blocks

I As long as the condition is valid, the loop body keeps executing. The condition isre-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 + xiters_left = iters_left - 1

>>> print x, 'squared is', ansSatyaki Sikdar© Programming in Python April 22 2016 46 / 137

Page 147: A 12 hour workshop on Introduction to Python

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 != 01 4 0 4 True2 4 4 3 True3 4 8 2 True4 4 12 1 True5 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

Page 148: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the correctness of the programIt’s very important to check if the procedure works for all x

I We’ve already proved that it works when x is a positive integer

I What about when x is 0? It works! The body of the while loop is not executed. So, ansstays at 0!

I What about when x is negative? Let’s see! Say x = -3.

test # x ans iters_left iters_left != 01 -3 0 -3 True2 -3 -3 -4 True3 -3 -6 -5 True4 -3 -9 -6 True5 -3 -12 -7 True6 -3 -15 -8 True

OOPS! It hasn’t stop when it’s supposed to! :(Satyaki Sikdar© Programming in Python April 22 2016 48 / 137

Page 149: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the correctness of the programIt’s very important to check if the procedure works for all x

I We’ve already proved that it works when x is a positive integer

I What about when x is 0? It works! The body of the while loop is not executed. So, ansstays at 0!

I What about when x is negative? Let’s see! Say x = -3.

test # x ans iters_left iters_left != 01 -3 0 -3 True2 -3 -3 -4 True3 -3 -6 -5 True4 -3 -9 -6 True5 -3 -12 -7 True6 -3 -15 -8 True

OOPS! It hasn’t stop when it’s supposed to! :(Satyaki Sikdar© Programming in Python April 22 2016 48 / 137

Page 150: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the correctness of the programIt’s very important to check if the procedure works for all x

I We’ve already proved that it works when x is a positive integer

I What about when x is 0? It works! The body of the while loop is not executed. So, ansstays at 0!

I What about when x is negative? Let’s see! Say x = -3.

test # x ans iters_left iters_left != 01 -3 0 -3 True2 -3 -3 -4 True3 -3 -6 -5 True4 -3 -9 -6 True5 -3 -12 -7 True6 -3 -15 -8 True

OOPS! It hasn’t stop when it’s supposed to! :(Satyaki Sikdar© Programming in Python April 22 2016 48 / 137

Page 151: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

does the code ever end??!!

I Things start to get a little fishy when x is negative

I Does the program ever end? NO!!

I Is it a problem? YES !!I 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', ansI 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

Page 152: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

does the code ever end??!!

I Things start to get a little fishy when x is negative

I Does the program ever end? NO!!

I Is it a problem? YES !!I 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', ansI 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

Page 153: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

does the code ever end??!!

I Things start to get a little fishy when x is negative

I Does the program ever end? NO!!

I Is it a problem? YES !!I 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', ansI 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

Page 154: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

does the code ever end??!!

I Things start to get a little fishy when x is negative

I Does the program ever end? NO!!

I Is it a problem? YES !!I 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', ansI 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

Page 155: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

does the code ever end??!!

I Things start to get a little fishy when x is negative

I Does the program ever end? NO!!

I Is it a problem? YES !!I 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', ansI 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

Page 156: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

for loops

I In Python, for loops are a little different. They are effectively for each loopsI Syntax:

for item in iterable:code block #notice the indentation

Strings are iterable. So are lists, tuples, dictionaries, sets, ...I 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

Page 157: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

for loops

I In Python, for loops are a little different. They are effectively for each loopsI Syntax:

for item in iterable:code block #notice the indentation

Strings are iterable. So are lists, tuples, dictionaries, sets, ...I 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

Page 158: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

for loops

I In Python, for loops are a little different. They are effectively for each loopsI Syntax:

for item in iterable:code block #notice the indentation

Strings are iterable. So are lists, tuples, dictionaries, sets, ...I 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

Page 159: A 12 hour workshop on Introduction to Python

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 notexhausted. 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

Page 160: A 12 hour workshop on Introduction to Python

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

Page 161: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 162: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 163: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 164: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 165: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 166: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

the xrange function

I An arithmetic series (AP) has parameters start, stop and step

I xrange() is used to generate an iterator for an AP in Python

I xrange(start, stop, step) will generate numbers of the form:start, start+ step, start+ 2 ∗ step, ..., in the set [start, end)

I 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

I 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

I 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

Page 167: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

loop condition evaluation

>>> x = 4>>> for j in range(x):

for i in range(x):print ix = 2

0123010101

I Seems bizarre? Let’s break it down

I The first range function is evaluated once with x = 4, socome what may, the outer loop will run 4 times

I Each time, the inner loop would run x times, so the firsttime it runs 4 times

I 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

Page 168: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

loop condition evaluation

>>> x = 4>>> for j in range(x):

for i in range(x):print ix = 2

0123010101

I Seems bizarre? Let’s break it down

I The first range function is evaluated once with x = 4, socome what may, the outer loop will run 4 times

I Each time, the inner loop would run x times, so the firsttime it runs 4 times

I 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

Page 169: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

loop condition evaluation

>>> x = 4>>> for j in range(x):

for i in range(x):print ix = 2

0123010101

I Seems bizarre? Let’s break it down

I The first range function is evaluated once with x = 4, socome what may, the outer loop will run 4 times

I Each time, the inner loop would run x times, so the firsttime it runs 4 times

I 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

Page 170: A 12 hour workshop on Introduction to Python

hour 2: ifs, buts and repeats looping constructs

loop condition evaluation

>>> x = 4>>> for j in range(x):

for i in range(x):print ix = 2

0123010101

I Seems bizarre? Let’s break it down

I The first range function is evaluated once with x = 4, socome what may, the outer loop will run 4 times

I Each time, the inner loop would run x times, so the firsttime it runs 4 times

I 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

Page 171: A 12 hour workshop on Introduction to Python

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:', ansnum_guess += 1if ans ** 2 < x:

low = anselse:

high = ansans = (low + high) / 2.0

>>> print ans, 'is close to sqrt of', x

Satyaki Sikdar© Programming in Python April 22 2016 55 / 137

Page 172: A 12 hour workshop on Introduction to Python

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

I What on earth is going on? Has Python gone nuts?Let’s dig deeper.

I In the memory, every number is stored in binary. Let’stry to figure out what’s the binary representation for (a)(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2

I (0.1)10 = (?)2? What about 332 = 0.9375? How about

25256? Turns out, no matter how many bits you use, youcan’t have a perfect 0.1 in memory! So round up!!

I So, now we know that x at the end is not a perfect 1, so the equality test fails

I But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’talway the actual value

Satyaki Sikdar© Programming in Python April 22 2016 56 / 137

Page 173: A 12 hour workshop on Introduction to Python

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

I What on earth is going on? Has Python gone nuts?Let’s dig deeper.

I In the memory, every number is stored in binary. Let’stry to figure out what’s the binary representation for (a)(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2

I (0.1)10 = (?)2? What about 332 = 0.9375? How about

25256? Turns out, no matter how many bits you use, youcan’t have a perfect 0.1 in memory! So round up!!

I So, now we know that x at the end is not a perfect 1, so the equality test fails

I But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’talway the actual value

Satyaki Sikdar© Programming in Python April 22 2016 56 / 137

Page 174: A 12 hour workshop on Introduction to Python

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

I What on earth is going on? Has Python gone nuts?Let’s dig deeper.

I In the memory, every number is stored in binary. Let’stry to figure out what’s the binary representation for (a)(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2

I (0.1)10 = (?)2? What about 332 = 0.9375? How about

25256? Turns out, no matter how many bits you use, youcan’t have a perfect 0.1 in memory! So round up!!

I So, now we know that x at the end is not a perfect 1, so the equality test fails

I But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’talway the actual value

Satyaki Sikdar© Programming in Python April 22 2016 56 / 137

Page 175: A 12 hour workshop on Introduction to Python

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

I What on earth is going on? Has Python gone nuts?Let’s dig deeper.

I In the memory, every number is stored in binary. Let’stry to figure out what’s the binary representation for (a)(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2

I (0.1)10 = (?)2? What about 332 = 0.9375? How about

25256? Turns out, no matter how many bits you use, youcan’t have a perfect 0.1 in memory! So round up!!

I So, now we know that x at the end is not a perfect 1, so the equality test fails

I But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’talway the actual value

Satyaki Sikdar© Programming in Python April 22 2016 56 / 137

Page 176: A 12 hour workshop on Introduction to Python

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

I What on earth is going on? Has Python gone nuts?Let’s dig deeper.

I In the memory, every number is stored in binary. Let’stry to figure out what’s the binary representation for (a)(0.5)10 => (0.1)2 and, (b) (0.625)10 => (0.101)2

I (0.1)10 = (?)2? What about 332 = 0.9375? How about

25256? Turns out, no matter how many bits you use, youcan’t have a perfect 0.1 in memory! So round up!!

I So, now we know that x at the end is not a perfect 1, so the equality test fails

I But why does it print 1.0 is not 1.0? Print does some rounding on it’s own! So, it doesn’talway the actual value

Satyaki Sikdar© Programming in Python April 22 2016 56 / 137

Page 177: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 178: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 179: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 180: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 181: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 182: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 lists

lists

I The list is a container that holds a number of other objects, in a given order.

I Similar to arrays in C, C++, Java, but it is more flexible. Lists are mutable

I Lists are enclosed in square brackets [ ] and the elements are separated by commas.Example: [1, 2, 3, 5] is a valid list

I It can contain anything that’s acceptable in Python. [1, ’two’, 3.0] is also a valid list

I Lists support indexing and slicing in the exact same manner as strings do.

I 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

Page 183: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

basic functions and operations

I Empty list is declared as [ ] or list()

I len() gives you the length of the list. So, len([1, 5, 6]) gives 3

I lst[i] returns the item at index i (the first item has index 0)

I Lists, unlike strings, support item assignment>>> lst = [1, 3, 4] >>> lst[1] = 7>>> print lst >>> print lst[1, 3, 4] [1, 7, 4]

I 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

Page 184: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

basic functions and operations

I Empty list is declared as [ ] or list()

I len() gives you the length of the list. So, len([1, 5, 6]) gives 3

I lst[i] returns the item at index i (the first item has index 0)

I Lists, unlike strings, support item assignment>>> lst = [1, 3, 4] >>> lst[1] = 7>>> print lst >>> print lst[1, 3, 4] [1, 7, 4]

I 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

Page 185: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

basic functions and operations

I Empty list is declared as [ ] or list()

I len() gives you the length of the list. So, len([1, 5, 6]) gives 3

I lst[i] returns the item at index i (the first item has index 0)

I Lists, unlike strings, support item assignment>>> lst = [1, 3, 4] >>> lst[1] = 7>>> print lst >>> print lst[1, 3, 4] [1, 7, 4]

I 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

Page 186: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

basic functions and operations

I Empty list is declared as [ ] or list()

I len() gives you the length of the list. So, len([1, 5, 6]) gives 3

I lst[i] returns the item at index i (the first item has index 0)

I Lists, unlike strings, support item assignment>>> lst = [1, 3, 4] >>> lst[1] = 7>>> print lst >>> print lst[1, 3, 4] [1, 7, 4]

I 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

Page 187: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

basic functions and operations

I Empty list is declared as [ ] or list()

I len() gives you the length of the list. So, len([1, 5, 6]) gives 3

I lst[i] returns the item at index i (the first item has index 0)

I Lists, unlike strings, support item assignment>>> lst = [1, 3, 4] >>> lst[1] = 7>>> print lst >>> print lst[1, 3, 4] [1, 7, 4]

I 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

Page 188: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds one element at a time. lst.append(1, 2) would raise an error!

I 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

Page 189: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds one element at a time. lst.append(1, 2) would raise an error!

I 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

Page 190: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds a new element only to the end

I Insert gives more flexibility. It allows you to specify the position as well

I Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done bylst.insert(0, x), and at the end by lst.insert(len(lst), x)

I 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

Page 191: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds a new element only to the end

I Insert gives more flexibility. It allows you to specify the position as well

I Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done bylst.insert(0, x), and at the end by lst.insert(len(lst), x)

I 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

Page 192: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds a new element only to the end

I Insert gives more flexibility. It allows you to specify the position as well

I Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done bylst.insert(0, x), and at the end by lst.insert(len(lst), x)

I 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

Page 193: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

I Append adds a new element only to the end

I Insert gives more flexibility. It allows you to specify the position as well

I Syntax: lst.insert(pos, new_element). So, insert at the beginning can be done bylst.insert(0, x), and at the end by lst.insert(len(lst), x)

I 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

Page 194: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

some more functions of lists

I list.remove(x): Remove the first item from the list whose value is x

I list.index(x): Return the index in the list of the first item whose value is x.

I list.count(x): Return the number of times x appears in the list.

I list.reverse(): Reverses the list in place

I list.sort(): Sorts the list in place in ascending order. For descending order, dolist.sort(reverse = True)

Satyaki Sikdar© Programming in Python April 22 2016 61 / 137

Page 195: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

some more functions of lists

I list.remove(x): Remove the first item from the list whose value is x

I list.index(x): Return the index in the list of the first item whose value is x.

I list.count(x): Return the number of times x appears in the list.

I list.reverse(): Reverses the list in place

I list.sort(): Sorts the list in place in ascending order. For descending order, dolist.sort(reverse = True)

Satyaki Sikdar© Programming in Python April 22 2016 61 / 137

Page 196: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

some more functions of lists

I list.remove(x): Remove the first item from the list whose value is x

I list.index(x): Return the index in the list of the first item whose value is x.

I list.count(x): Return the number of times x appears in the list.

I list.reverse(): Reverses the list in place

I list.sort(): Sorts the list in place in ascending order. For descending order, dolist.sort(reverse = True)

Satyaki Sikdar© Programming in Python April 22 2016 61 / 137

Page 197: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

some more functions of lists

I list.remove(x): Remove the first item from the list whose value is x

I list.index(x): Return the index in the list of the first item whose value is x.

I list.count(x): Return the number of times x appears in the list.

I list.reverse(): Reverses the list in place

I list.sort(): Sorts the list in place in ascending order. For descending order, dolist.sort(reverse = True)

Satyaki Sikdar© Programming in Python April 22 2016 61 / 137

Page 198: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list operations

some more functions of lists

I list.remove(x): Remove the first item from the list whose value is x

I list.index(x): Return the index in the list of the first item whose value is x.

I list.count(x): Return the number of times x appears in the list.

I list.reverse(): Reverses the list in place

I list.sort(): Sorts the list in place in ascending order. For descending order, dolist.sort(reverse = True)

Satyaki Sikdar© Programming in Python April 22 2016 61 / 137

Page 199: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list comprehension

list comprehension and range()

I 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]

I 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

Page 200: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 list comprehension

list comprehension and range()

I 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]

I 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

Page 201: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuples

I A tuple is a sequence of values. Enclosed by parentheses

I The values can be any type, and they are indexed by integers, so, tuples are a lot like lists

I 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')

I 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

Page 202: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuples

I A tuple is a sequence of values. Enclosed by parentheses

I The values can be any type, and they are indexed by integers, so, tuples are a lot like lists

I 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')

I 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

Page 203: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuples

I A tuple is a sequence of values. Enclosed by parentheses

I The values can be any type, and they are indexed by integers, so, tuples are a lot like lists

I 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')

I 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

Page 204: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuples

I A tuple is a sequence of values. Enclosed by parentheses

I The values can be any type, and they are indexed by integers, so, tuples are a lot like lists

I 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')

I 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

Page 205: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I Most list operators also work on tuples. The bracket operator indexes an element>>> t = ('a', 'b', 'c', 'd', 'e')>>> print t[0]a

I Slice operator selects a range of elements.>>> print t[1: 3]('b', 'c')

I 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

Page 206: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I Most list operators also work on tuples. The bracket operator indexes an element>>> t = ('a', 'b', 'c', 'd', 'e')>>> print t[0]a

I Slice operator selects a range of elements.>>> print t[1: 3]('b', 'c')

I 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

Page 207: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I Most list operators also work on tuples. The bracket operator indexes an element>>> t = ('a', 'b', 'c', 'd', 'e')>>> print t[0]a

I Slice operator selects a range of elements.>>> print t[1: 3]('b', 'c')

I 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

Page 208: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

packing and unpacking tuples

I With conventional assignments, you have to use a temp variable>>> temp = a>>> a = b>>> b = temp

I This solution is cumbersome; tuple assignment is more elegant>>> a, b = b, a

I The left side is a tuple of variables, the right side is a tuple of expressions

I The number of variables on the left and the number of values on the right have to be thesame:>>> a, b = 1, 2, 3ValueError: too many values to unpack

Satyaki Sikdar© Programming in Python April 22 2016 65 / 137

Page 209: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

packing and unpacking tuples

I With conventional assignments, you have to use a temp variable>>> temp = a>>> a = b>>> b = temp

I This solution is cumbersome; tuple assignment is more elegant>>> a, b = b, a

I The left side is a tuple of variables, the right side is a tuple of expressions

I The number of variables on the left and the number of values on the right have to be thesame:>>> a, b = 1, 2, 3ValueError: too many values to unpack

Satyaki Sikdar© Programming in Python April 22 2016 65 / 137

Page 210: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

packing and unpacking tuples

I With conventional assignments, you have to use a temp variable>>> temp = a>>> a = b>>> b = temp

I This solution is cumbersome; tuple assignment is more elegant>>> a, b = b, a

I The left side is a tuple of variables, the right side is a tuple of expressions

I The number of variables on the left and the number of values on the right have to be thesame:>>> a, b = 1, 2, 3ValueError: too many values to unpack

Satyaki Sikdar© Programming in Python April 22 2016 65 / 137

Page 211: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

packing and unpacking tuples

I With conventional assignments, you have to use a temp variable>>> temp = a>>> a = b>>> b = temp

I This solution is cumbersome; tuple assignment is more elegant>>> a, b = b, a

I The left side is a tuple of variables, the right side is a tuple of expressions

I The number of variables on the left and the number of values on the right have to be thesame:>>> a, b = 1, 2, 3ValueError: too many values to unpack

Satyaki Sikdar© Programming in Python April 22 2016 65 / 137

Page 212: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

lists and tuples

I zip takes two or more sequences and “zips” them into a list of tuples where each tuplecontains one element from each sequence>>> s = 'abc'>>> t = [0, 1, 2]>>> zip(s, t)[('a, 0), ('b', 1), ('c', 2)]

I 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

Page 213: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

lists and tuples

I zip takes two or more sequences and “zips” them into a list of tuples where each tuplecontains one element from each sequence>>> s = 'abc'>>> t = [0, 1, 2]>>> zip(s, t)[('a, 0), ('b', 1), ('c', 2)]

I 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

Page 214: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I 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, letter0 a1 b2 c

I Combine zip, for and tuple assignment to traverse two (or more) sequencesdef has_match(t1, t2):

for x, y in zip(t1, t2):if x == y:

return Truereturn False

I To traverse the elements of a sequence and their indices, use enumerate:>>> for idx, ele in enumerate('abc'):

print idx, eleSatyaki Sikdar© Programming in Python April 22 2016 67 / 137

Page 215: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I 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, letter0 a1 b2 c

I Combine zip, for and tuple assignment to traverse two (or more) sequencesdef has_match(t1, t2):

for x, y in zip(t1, t2):if x == y:

return Truereturn False

I To traverse the elements of a sequence and their indices, use enumerate:>>> for idx, ele in enumerate('abc'):

print idx, eleSatyaki Sikdar© Programming in Python April 22 2016 67 / 137

Page 216: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

I 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, letter0 a1 b2 c

I Combine zip, for and tuple assignment to traverse two (or more) sequencesdef has_match(t1, t2):

for x, y in zip(t1, t2):if x == y:

return Truereturn False

I To traverse the elements of a sequence and their indices, use enumerate:>>> for idx, ele in enumerate('abc'):

print idx, eleSatyaki Sikdar© Programming in Python April 22 2016 67 / 137

Page 217: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

tuple comparisons

I The relational operators work with tuples and other seqs

I Python starts by comparing the first element from each seq. If they are equal, it goes onto the next elements, and so on

>>> (0, 1, 2) < (0, 3, 4)True>>> (0, 1, 2000000) < (0, 3, 4)True

I 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

Page 218: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

tuple comparisons

I The relational operators work with tuples and other seqs

I Python starts by comparing the first element from each seq. If they are equal, it goes onto the next elements, and so on

>>> (0, 1, 2) < (0, 3, 4)True>>> (0, 1, 2000000) < (0, 3, 4)True

I 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

Page 219: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 tuple operations

tuple comparisons

I The relational operators work with tuples and other seqs

I Python starts by comparing the first element from each seq. If they are equal, it goes onto the next elements, and so on

>>> (0, 1, 2) < (0, 3, 4)True>>> (0, 1, 2000000) < (0, 3, 4)True

I 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

Page 220: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 functions

functions

I We’ve already used some pre-defined functions already! len(), range(), abs(), count(), andso on..

I Python allows you to make your own functions! YAY!

I Each function definition is of the formdef name of function (list_of_parameters):

body of the functionreturn things

I A function can return things too! And in Python, every function returns something. Youcan tell the function to return something that you want! By default it’s None

I Notice there’s no mention of the return type

Satyaki Sikdar© Programming in Python April 22 2016 69 / 137

Page 221: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 functions

functions

I We’ve already used some pre-defined functions already! len(), range(), abs(), count(), andso on..

I Python allows you to make your own functions! YAY!

I Each function definition is of the formdef name of function (list_of_parameters):

body of the functionreturn things

I A function can return things too! And in Python, every function returns something. Youcan tell the function to return something that you want! By default it’s None

I Notice there’s no mention of the return type

Satyaki Sikdar© Programming in Python April 22 2016 69 / 137

Page 222: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 functions

functions

I We’ve already used some pre-defined functions already! len(), range(), abs(), count(), andso on..

I Python allows you to make your own functions! YAY!

I Each function definition is of the formdef name of function (list_of_parameters):

body of the functionreturn things

I A function can return things too! And in Python, every function returns something. Youcan tell the function to return something that you want! By default it’s None

I Notice there’s no mention of the return type

Satyaki Sikdar© Programming in Python April 22 2016 69 / 137

Page 223: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 functions

functions

I We’ve already used some pre-defined functions already! len(), range(), abs(), count(), andso on..

I Python allows you to make your own functions! YAY!

I Each function definition is of the formdef name of function (list_of_parameters):

body of the functionreturn things

I A function can return things too! And in Python, every function returns something. Youcan tell the function to return something that you want! By default it’s None

I Notice there’s no mention of the return type

Satyaki Sikdar© Programming in Python April 22 2016 69 / 137

Page 224: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 functions

functions

I We’ve already used some pre-defined functions already! len(), range(), abs(), count(), andso on..

I Python allows you to make your own functions! YAY!

I Each function definition is of the formdef name of function (list_of_parameters):

body of the functionreturn things

I A function can return things too! And in Python, every function returns something. Youcan tell the function to return something that you want! By default it’s None

I Notice there’s no mention of the return type

Satyaki Sikdar© Programming in Python April 22 2016 69 / 137

Page 225: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 an example

An easy exampledef maximum(x, y):

'''returns the maximum of the two arguments'''if x > y:

return xelse:

return y>>> print maximum(10, 20)20

I A function can have any name (barring the reserved words)

I 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

Page 226: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 an example

An easy exampledef maximum(x, y):

'''returns the maximum of the two arguments'''if x > y:

return xelse:

return y>>> print maximum(10, 20)20

I A function can have any name (barring the reserved words)

I 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

Page 227: A 12 hour workshop on Introduction to Python

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 ismaximum(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 encounteredor 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

Page 228: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 keyword arguments

Arguments and default valuesThere 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 formalto the second actual and so on

2 Keyword arguments: formals are bound to actuals using the name of the formalparameter

def print_name(first_name, last_name, reverse):if reverse:

print last_name + ', ' + first_nameelse:

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

Page 229: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 keyword arguments

arguments contd.

I The order of the keyword arguments does not matter. So, print_name(last_name =’Jackman’, first_name = ’Hugh’, reverse = False) is valid

I But, you can’t follow up a keyword argument with a non keyword argument. Thatconfuses 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

Page 230: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 keyword arguments

arguments contd.

I The order of the keyword arguments does not matter. So, print_name(last_name =’Jackman’, first_name = ’Hugh’, reverse = False) is valid

I But, you can’t follow up a keyword argument with a non keyword argument. Thatconfuses 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

Page 231: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

scope of variables in functions

def f(x): #x is a formal parametery = 1x = x + yprint 'x = ', xreturn 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

Page 232: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

so what’s going on here?

Surely, x is surely misbehaving?! Or is it?I the two x’s are not really the same! They might have the same name, but they are

different!

I Kinda like how you find someone on facebook with your name but then that person hasnothing to do with you!

I The concept of name space comes into play

I The variables in the function f exist only when f is executing. When the control returnsback from the function, it goes back to the variables defined previously.

Satyaki Sikdar© Programming in Python April 22 2016 75 / 137

Page 233: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

so what’s going on here?

Surely, x is surely misbehaving?! Or is it?I the two x’s are not really the same! They might have the same name, but they are

different!

I Kinda like how you find someone on facebook with your name but then that person hasnothing to do with you!

I The concept of name space comes into play

I The variables in the function f exist only when f is executing. When the control returnsback from the function, it goes back to the variables defined previously.

Satyaki Sikdar© Programming in Python April 22 2016 75 / 137

Page 234: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

so what’s going on here?

Surely, x is surely misbehaving?! Or is it?I the two x’s are not really the same! They might have the same name, but they are

different!

I Kinda like how you find someone on facebook with your name but then that person hasnothing to do with you!

I The concept of name space comes into play

I The variables in the function f exist only when f is executing. When the control returnsback from the function, it goes back to the variables defined previously.

Satyaki Sikdar© Programming in Python April 22 2016 75 / 137

Page 235: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

so what’s going on here?

Surely, x is surely misbehaving?! Or is it?I the two x’s are not really the same! They might have the same name, but they are

different!

I Kinda like how you find someone on facebook with your name but then that person hasnothing to do with you!

I The concept of name space comes into play

I The variables in the function f exist only when f is executing. When the control returnsback from the function, it goes back to the variables defined previously.

Satyaki Sikdar© Programming in Python April 22 2016 75 / 137

Page 236: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

returning a bunch of things

I Python allows functions to return more than one thingdef 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 a9>>> print b27

I This paradigm, though simple, is very powerful

Satyaki Sikdar© Programming in Python April 22 2016 76 / 137

Page 237: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 scope

returning a bunch of things

I Python allows functions to return more than one thingdef 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 a9>>> print b27

I This paradigm, though simple, is very powerful

Satyaki Sikdar© Programming in Python April 22 2016 76 / 137

Page 238: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 239: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 240: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 241: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 242: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 243: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 sets

set

I A set is an unordered collection of distinct, immutable valuesI {′Alice′, 3.1415,′ Carol′} is a set of 3 elementsI {′Dean′} is a singleton set

>>> cset = {11, 11, 22}>>> csetset([11, 22])

I Sets are mutable - can add or remove things on the flyI Insertion using addI Deletion using remove or discard

>>> st = {'Jon', 'Arya'}>>> st.add('Jaime') >>> st.remove('Jon')>>> print st >>> print stset(['Jon', 'Arya', 'Jaime']) set(['Arya', 'Jaime'])

Satyaki Sikdar© Programming in Python April 22 2016 77 / 137

Page 244: A 12 hour workshop on Introduction to Python

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 unionset(['Stokes', 'Hales', 'Ali', 'Broad', 'Roy', 'Cook', 'Root'])>>> print test_team & odi_team #set intersectionset(['Stokes', 'Root', 'Ali'])>>> test_team - odi_team #set differnceset(['Cook', 'Broad'])>>> test_team ^ odi_team #symmetric differenceset(['Hales', 'Broad', 'Roy', 'Cook'])

Satyaki Sikdar© Programming in Python April 22 2016 78 / 137

Page 245: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 set operations

set operations

I Sets do not support indexing!>>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'}>>> mysetset(['Toronto', 'Amsterdam', 'Winnipeg'])>>> myset[0]TypeError: 'set' object does not support indexing

I + operator doesn’t work with sets>>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'}>>> myset2 = {'Brussels', 'Hamilton'}>>> myset1 + myset2TypeError: unsupported operand type(s) for +: 'set' and 'set'

Satyaki Sikdar© Programming in Python April 22 2016 79 / 137

Page 246: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 set operations

set operations

I Sets do not support indexing!>>> myset = {'Amsterdam', 'Winnipeg', 'Toronto'}>>> mysetset(['Toronto', 'Amsterdam', 'Winnipeg'])>>> myset[0]TypeError: 'set' object does not support indexing

I + operator doesn’t work with sets>>> myset1 = {'Amsterdam', 'Winnipeg', 'Toronto'}>>> myset2 = {'Brussels', 'Hamilton'}>>> myset1 + myset2TypeError: unsupported operand type(s) for +: 'set' and 'set'

Satyaki Sikdar© Programming in Python April 22 2016 79 / 137

Page 247: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionaries

dictionary

I A dictionary is like a list, but more general - a personal favorite

I In a list, the indices have to be integers; in a dictionary they can be (almost) any type

I The keys must be immutable

I Let’s build a dictionary that maps from English to Spanish words. Keys and values areboth strings

>>> eng2sp = dict() # or eng2sp = {}>>> print eng2sp{}

Satyaki Sikdar© Programming in Python April 22 2016 80 / 137

Page 248: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionaries

dictionary

I A dictionary is like a list, but more general - a personal favorite

I In a list, the indices have to be integers; in a dictionary they can be (almost) any type

I The keys must be immutable

I Let’s build a dictionary that maps from English to Spanish words. Keys and values areboth strings

>>> eng2sp = dict() # or eng2sp = {}>>> print eng2sp{}

Satyaki Sikdar© Programming in Python April 22 2016 80 / 137

Page 249: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionaries

dictionary

I A dictionary is like a list, but more general - a personal favorite

I In a list, the indices have to be integers; in a dictionary they can be (almost) any type

I The keys must be immutable

I Let’s build a dictionary that maps from English to Spanish words. Keys and values areboth strings

>>> eng2sp = dict() # or eng2sp = {}>>> print eng2sp{}

Satyaki Sikdar© Programming in Python April 22 2016 80 / 137

Page 250: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionaries

dictionary

I A dictionary is like a list, but more general - a personal favorite

I In a list, the indices have to be integers; in a dictionary they can be (almost) any type

I The keys must be immutable

I Let’s build a dictionary that maps from English to Spanish words. Keys and values areboth strings

>>> eng2sp = dict() # or eng2sp = {}>>> print eng2sp{}

Satyaki Sikdar© Programming in Python April 22 2016 80 / 137

Page 251: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I To add items to the dictionary, use square brackets>>> eng2sp['one'] = 'uno'

I Creates an item that maps from the key ’one’ to the value ’uno’>>> print eng2sp{'one': 'uno'}

I Instantiate a dictionary with multiple items like>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}>>> print eng2sp{'one': 'uno', 'three': 'tres', 'two': 'dos'}

I The order of key-value pairs is not the same

Satyaki Sikdar© Programming in Python April 22 2016 81 / 137

Page 252: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I To add items to the dictionary, use square brackets>>> eng2sp['one'] = 'uno'

I Creates an item that maps from the key ’one’ to the value ’uno’>>> print eng2sp{'one': 'uno'}

I Instantiate a dictionary with multiple items like>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}>>> print eng2sp{'one': 'uno', 'three': 'tres', 'two': 'dos'}

I The order of key-value pairs is not the same

Satyaki Sikdar© Programming in Python April 22 2016 81 / 137

Page 253: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I To add items to the dictionary, use square brackets>>> eng2sp['one'] = 'uno'

I Creates an item that maps from the key ’one’ to the value ’uno’>>> print eng2sp{'one': 'uno'}

I Instantiate a dictionary with multiple items like>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}>>> print eng2sp{'one': 'uno', 'three': 'tres', 'two': 'dos'}

I The order of key-value pairs is not the same

Satyaki Sikdar© Programming in Python April 22 2016 81 / 137

Page 254: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I To add items to the dictionary, use square brackets>>> eng2sp['one'] = 'uno'

I Creates an item that maps from the key ’one’ to the value ’uno’>>> print eng2sp{'one': 'uno'}

I Instantiate a dictionary with multiple items like>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}>>> print eng2sp{'one': 'uno', 'three': 'tres', 'two': 'dos'}

I The order of key-value pairs is not the same

Satyaki Sikdar© Programming in Python April 22 2016 81 / 137

Page 255: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

constraints on keys and values

I Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys

I Ints, floats, strings, tuples, frozensets are fine!

I 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

Page 256: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

constraints on keys and values

I Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys

I Ints, floats, strings, tuples, frozensets are fine!

I 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

Page 257: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

constraints on keys and values

I Keys in a dictionary must be immutable. So, lists, sets, dictionaries cannot be keys

I Ints, floats, strings, tuples, frozensets are fine!

I 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

Page 258: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I Indexing is done solely using the keys>>> print eng2sp['two']dos

I If the key isn’t in the dictionary, you get an exception>>> print eng2sp['four']KeyError: 'four'

I len function returns the number of key-value pairs>>> len(eng2sp)3

I in tells you whether something appears as a key in the dictionary (appearing as a value isnot good enough)>>> 'one' in eng2sp >>> 'uno' in eng2spTrue False

Satyaki Sikdar© Programming in Python April 22 2016 83 / 137

Page 259: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I Indexing is done solely using the keys>>> print eng2sp['two']dos

I If the key isn’t in the dictionary, you get an exception>>> print eng2sp['four']KeyError: 'four'

I len function returns the number of key-value pairs>>> len(eng2sp)3

I in tells you whether something appears as a key in the dictionary (appearing as a value isnot good enough)>>> 'one' in eng2sp >>> 'uno' in eng2spTrue False

Satyaki Sikdar© Programming in Python April 22 2016 83 / 137

Page 260: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I Indexing is done solely using the keys>>> print eng2sp['two']dos

I If the key isn’t in the dictionary, you get an exception>>> print eng2sp['four']KeyError: 'four'

I len function returns the number of key-value pairs>>> len(eng2sp)3

I in tells you whether something appears as a key in the dictionary (appearing as a value isnot good enough)>>> 'one' in eng2sp >>> 'uno' in eng2spTrue False

Satyaki Sikdar© Programming in Python April 22 2016 83 / 137

Page 261: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I Indexing is done solely using the keys>>> print eng2sp['two']dos

I If the key isn’t in the dictionary, you get an exception>>> print eng2sp['four']KeyError: 'four'

I len function returns the number of key-value pairs>>> len(eng2sp)3

I in tells you whether something appears as a key in the dictionary (appearing as a value isnot good enough)>>> 'one' in eng2sp >>> 'uno' in eng2spTrue False

Satyaki Sikdar© Programming in Python April 22 2016 83 / 137

Page 262: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

deleting things

I 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'}

I 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

Page 263: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

deleting things

I 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'}

I 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

Page 264: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I 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)]

I 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}

I 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

Page 265: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I 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)]

I 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}

I 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

Page 266: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 dictionary manipulations

I 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)]

I 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}

I 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

Page 267: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

countersI 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 anindex 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

Page 268: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

countersI 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 anindex 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

Page 269: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

countersI 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 anindex 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

Page 270: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

countersI 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 anindex 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

Page 271: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

inverting a dictionary

I Given a dict that maps letters to freq, create a dict that maps freq to letters

I Several letters may have the same freq, so each value must be a listdef 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

Page 272: A 12 hour workshop on Introduction to Python

hour 3: data structures 101 counters

inverting a dictionary

I Given a dict that maps letters to freq, create a dict that maps freq to letters

I Several letters may have the same freq, so each value must be a listdef 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

Page 273: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion

Satyaki Sikdar© Programming in Python April 22 2016 88 / 137

Page 274: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 introduction

what is it anyway?

I It’s a method where the solution to a problem depends on solutions to smaller instances ofthe same problem

I Some problems are inherently recursive Let’s see an example. The legal code of the USdefines a natural born citizen roughly as follows:

I Any child born inside the United States

I Any child born in wedlock outside the United States both of whose parents are citizens of theUS, as long as one parent has lived in the US prior to the birth of the child, and

I Any child born in wedlock outside the US one of whose parents is a US citizen who has livedat least five years, .... so on

Satyaki Sikdar© Programming in Python April 22 2016 89 / 137

Page 275: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 introduction

what is it anyway?

I It’s a method where the solution to a problem depends on solutions to smaller instances ofthe same problem

I Some problems are inherently recursive Let’s see an example. The legal code of the USdefines a natural born citizen roughly as follows:

I Any child born inside the United States

I Any child born in wedlock outside the United States both of whose parents are citizens of theUS, as long as one parent has lived in the US prior to the birth of the child, and

I Any child born in wedlock outside the US one of whose parents is a US citizen who has livedat least five years, .... so on

Satyaki Sikdar© Programming in Python April 22 2016 89 / 137

Page 276: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 introduction

what is it anyway?

I It’s a method where the solution to a problem depends on solutions to smaller instances ofthe same problem

I Some problems are inherently recursive Let’s see an example. The legal code of the USdefines a natural born citizen roughly as follows:

I Any child born inside the United States

I Any child born in wedlock outside the United States both of whose parents are citizens of theUS, as long as one parent has lived in the US prior to the birth of the child, and

I Any child born in wedlock outside the US one of whose parents is a US citizen who has livedat least five years, .... so on

Satyaki Sikdar© Programming in Python April 22 2016 89 / 137

Page 277: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 introduction

what is it anyway?

I It’s a method where the solution to a problem depends on solutions to smaller instances ofthe same problem

I Some problems are inherently recursive Let’s see an example. The legal code of the USdefines a natural born citizen roughly as follows:

I Any child born inside the United States

I Any child born in wedlock outside the United States both of whose parents are citizens of theUS, as long as one parent has lived in the US prior to the birth of the child, and

I Any child born in wedlock outside the US one of whose parents is a US citizen who has livedat least five years, .... so on

Satyaki Sikdar© Programming in Python April 22 2016 89 / 137

Page 278: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 introduction

what is it anyway?

I It’s a method where the solution to a problem depends on solutions to smaller instances ofthe same problem

I Some problems are inherently recursive Let’s see an example. The legal code of the USdefines a natural born citizen roughly as follows:

I Any child born inside the United States

I Any child born in wedlock outside the United States both of whose parents are citizens of theUS, as long as one parent has lived in the US prior to the birth of the child, and

I Any child born in wedlock outside the US one of whose parents is a US citizen who has livedat least five years, .... so on

Satyaki Sikdar© Programming in Python April 22 2016 89 / 137

Page 279: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 the structure

The structure of a generic recursive code

def rec_function(parameters):if bool_expr1: # base case 1

return somethingif bool_expr2: # base case 2

return something_elsedo_something_funkyinductive_case #call rec_function() with reduced parameters

IMPORTANT:1 The base cases must terminate the flow of code and return something meaningful2 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

Page 280: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

example 1

Mathematically,

n! =

{n ∗ (n− 1)! if n > 1

1 otherwise

def factR(n):'''computes n! recursivelyn >=0'''if n <= 1:

return 1else:

return n * factorial(n - 1)

def factI(n):'''computes n! iterativelyn >=0'''result = 1while n > 1:

result = result * nn -= 1

return resultSatyaki Sikdar© Programming in Python April 22 2016 91 / 137

Page 281: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

how does it work?

Say you are calling factorial(3). Let’s see what happens!

I factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)

I factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)

I factorial(1) is called. Hits the base case! No further calls to factorial. Time to trackback. factorial(1) returns 1

I factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)returns 2 x 1

I factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3x 2 => 6 And we are done!

Satyaki Sikdar© Programming in Python April 22 2016 92 / 137

Page 282: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

how does it work?

Say you are calling factorial(3). Let’s see what happens!

I factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)

I factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)

I factorial(1) is called. Hits the base case! No further calls to factorial. Time to trackback. factorial(1) returns 1

I factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)returns 2 x 1

I factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3x 2 => 6 And we are done!

Satyaki Sikdar© Programming in Python April 22 2016 92 / 137

Page 283: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

how does it work?

Say you are calling factorial(3). Let’s see what happens!

I factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)

I factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)

I factorial(1) is called. Hits the base case! No further calls to factorial. Time to trackback. factorial(1) returns 1

I factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)returns 2 x 1

I factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3x 2 => 6 And we are done!

Satyaki Sikdar© Programming in Python April 22 2016 92 / 137

Page 284: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

how does it work?

Say you are calling factorial(3). Let’s see what happens!

I factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)

I factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)

I factorial(1) is called. Hits the base case! No further calls to factorial. Time to trackback. factorial(1) returns 1

I factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)returns 2 x 1

I factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3x 2 => 6 And we are done!

Satyaki Sikdar© Programming in Python April 22 2016 92 / 137

Page 285: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 illustrations

how does it work?

Say you are calling factorial(3). Let’s see what happens!

I factorial(3) is called. It returns 3 x factorial(2). factorial(3) => factorial(2)

I factorial(2) is called. It returns 2 x factorial(1). factorial(2) => factorial(1)

I factorial(1) is called. Hits the base case! No further calls to factorial. Time to trackback. factorial(1) returns 1

I factorial(2) is calculated as 2 x factorial(1) and we know what factorial is, so factorial(2)returns 2 x 1

I factorial(3) can be calculated as we know factorial(2) and it returns 3 x factorial(2) => 3x 2 => 6 And we are done!

Satyaki Sikdar© Programming in Python April 22 2016 92 / 137

Page 286: A 12 hour workshop on Introduction to Python

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 bereached? 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

Page 287: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

implementation

def factorial(n):if n == 0:

return 1else:

return factorial(n + 1) / (n + 1)

>>> factorial(4) => Something nasty!RuntimeError: maximum recursion depth exceeded

I It’s no surprise that factorial(4) fails. The same thing happens whenever the argument isnon zero.

I So, who’s to blame? The innocent looking recurrence relation? Yeah

Satyaki Sikdar© Programming in Python April 22 2016 94 / 137

Page 288: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

implementation

def factorial(n):if n == 0:

return 1else:

return factorial(n + 1) / (n + 1)

>>> factorial(4) => Something nasty!RuntimeError: maximum recursion depth exceeded

I It’s no surprise that factorial(4) fails. The same thing happens whenever the argument isnon zero.

I So, who’s to blame? The innocent looking recurrence relation? Yeah

Satyaki Sikdar© Programming in Python April 22 2016 94 / 137

Page 289: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

how to fix this mess?!

I Can the base case ever be reached with n > 0 ? NO!

I So, as a consequence, the program doesn’t stop until you run out of stack space!

I Stack overflow is the recursive equivalent to an infinite loop in iteration

I Fix the recurrence relation to get the correct results.

Satyaki Sikdar© Programming in Python April 22 2016 95 / 137

Page 290: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

how to fix this mess?!

I Can the base case ever be reached with n > 0 ? NO!

I So, as a consequence, the program doesn’t stop until you run out of stack space!

I Stack overflow is the recursive equivalent to an infinite loop in iteration

I Fix the recurrence relation to get the correct results.

Satyaki Sikdar© Programming in Python April 22 2016 95 / 137

Page 291: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

how to fix this mess?!

I Can the base case ever be reached with n > 0 ? NO!

I So, as a consequence, the program doesn’t stop until you run out of stack space!

I Stack overflow is the recursive equivalent to an infinite loop in iteration

I Fix the recurrence relation to get the correct results.

Satyaki Sikdar© Programming in Python April 22 2016 95 / 137

Page 292: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion woes

how to fix this mess?!

I Can the base case ever be reached with n > 0 ? NO!

I So, as a consequence, the program doesn’t stop until you run out of stack space!

I Stack overflow is the recursive equivalent to an infinite loop in iteration

I Fix the recurrence relation to get the correct results.

Satyaki Sikdar© Programming in Python April 22 2016 95 / 137

Page 293: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 294: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 295: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 296: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 297: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 298: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 299: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 300: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 fibonacci numbers

they breed like bunnies!

I Leonardo of Pisa, known as Fibonacci quantified this notion, albeit with some terribleassumptions

I The assumptionsI Bunnies are able to mate when they are 1 month old

I They have a 1 month gestation period

I They are immortal

I Each female gives birth to one male and one female bunniesevery time

I Two bunnies, a male and a female are put in an exhibitI The question is, how many pregnant bunnies would there be

at the end of say n months?

Month n Females Fn

0 11 12 23 34 55 86 13

Satyaki Sikdar© Programming in Python April 22 2016 96 / 137

Page 301: A 12 hour workshop on Introduction to Python

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 0elif n == 1:

return 1else:

return fibo(n - 1) + fibo(n - 2)

Satyaki Sikdar© Programming in Python April 22 2016 97 / 137

Page 302: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 recursion tree

recursion tree

Figure: Recursion tree for fib(7)

Satyaki Sikdar© Programming in Python April 22 2016 98 / 137

Page 303: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 speeding up

speed of computation

I Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?

I Let’s take another look at the recursion tree

I 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

Page 304: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 speeding up

speed of computation

I Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?

I Let’s take another look at the recursion tree

I 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

Page 305: A 12 hour workshop on Introduction to Python

hour 4: confusion 101 speeding up

speed of computation

I Try to print the 40th Fibonacci number. It takes time doesn’t it? Can you figure out why?

I Let’s take another look at the recursion tree

I 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

Page 306: A 12 hour workshop on Introduction to Python

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]

I Is this approach better? YES!

I Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2calls to the ans list.

I Try calculating the 40th Fibonacci number again! Much faster, isn’t it?

Satyaki Sikdar© Programming in Python April 22 2016 100 / 137

Page 307: A 12 hour workshop on Introduction to Python

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]

I Is this approach better? YES!

I Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2calls to the ans list.

I Try calculating the 40th Fibonacci number again! Much faster, isn’t it?

Satyaki Sikdar© Programming in Python April 22 2016 100 / 137

Page 308: A 12 hour workshop on Introduction to Python

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]

I Is this approach better? YES!

I Are we saving computations? Yeah, the ans list stores the previous results. It takes only 2calls to the ans list.

I Try calculating the 40th Fibonacci number again! Much faster, isn’t it?

Satyaki Sikdar© Programming in Python April 22 2016 100 / 137

Page 309: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 310: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 311: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 312: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 313: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 314: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 315: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy intro to OOP

object oriented programming

I So far, we have seen a lot of Python’s own data structures and types. What if we needspecialized structures which are not natively provided in Py?

I We have the power of defining our own type!

I Let’s see an example. Say we want to represent a point in 2-D space. What are ouroptions?

I Store the coordinates x and y in two variables x and yI Store the coordinates as elements in a list or tupleI Create a new type to represent points as specialized things called objects

I Creating a new type is (a little) more complicated than the other options, but it hasadvantages that will be apparent soon

Satyaki Sikdar© Programming in Python April 22 2016 101 / 137

Page 316: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 317: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 318: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 319: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 320: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 321: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

classes

I A user-defined type is also called a class. A class defintion looks like thisclass Point:

"""Represents a point in 2-D space."""

I This header indicates that the new class is a Point

I The body is a docstring that explains what the class is for

I We can define variables and functions inside a class definition

I The class is like a factory for creating objectsI 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

Page 322: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

attributes

I You can assign values to an instance using dot notation>>> blank.x = 3.0>>> blank.y = 4.0

I You can read the value of an attribute using the same syntax>>> print blank.y4.0>>> x = blank.x>>> print x3.0

Figure: Object diagram

I The expression blank.x means, “Go to the object blank refers to and get the value of x”I 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

Page 323: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

attributes

I You can assign values to an instance using dot notation>>> blank.x = 3.0>>> blank.y = 4.0

I You can read the value of an attribute using the same syntax>>> print blank.y4.0>>> x = blank.x>>> print x3.0

Figure: Object diagram

I The expression blank.x means, “Go to the object blank refers to and get the value of x”I 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

Page 324: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

attributes

I You can assign values to an instance using dot notation>>> blank.x = 3.0>>> blank.y = 4.0

I You can read the value of an attribute using the same syntax>>> print blank.y4.0>>> x = blank.x>>> print x3.0

Figure: Object diagram

I The expression blank.x means, “Go to the object blank refers to and get the value of x”I 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

Page 325: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

attributes

I You can assign values to an instance using dot notation>>> blank.x = 3.0>>> blank.y = 4.0

I You can read the value of an attribute using the same syntax>>> print blank.y4.0>>> x = blank.x>>> print x3.0

Figure: Object diagram

I The expression blank.x means, “Go to the object blank refers to and get the value of x”I 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

Page 326: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

I If you try to access an attribute that doesn’t exist, you get an AttributeError

I If you are not sure what type an object is, you can use the type function

I If you are not sure whether an object has a particular attribute, you can use the built-infunction hasattr

>>> p = Point()>>> p.x = 5.5>>> p.y = 2.2>>> print p.x5.5>>> print p.y2.2>>> print p.zAttributeError: 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

Page 327: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

I If you try to access an attribute that doesn’t exist, you get an AttributeError

I If you are not sure what type an object is, you can use the type function

I If you are not sure whether an object has a particular attribute, you can use the built-infunction hasattr

>>> p = Point()>>> p.x = 5.5>>> p.y = 2.2>>> print p.x5.5>>> print p.y2.2>>> print p.zAttributeError: 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

Page 328: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy class

I If you try to access an attribute that doesn’t exist, you get an AttributeError

I If you are not sure what type an object is, you can use the type function

I If you are not sure whether an object has a particular attribute, you can use the built-infunction hasattr

>>> p = Point()>>> p.x = 5.5>>> p.y = 2.2>>> print p.x5.5>>> print p.y2.2>>> print p.zAttributeError: 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

Page 329: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I 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

I You can pass an instance as an argument in the usual waydef print_point(p):

print '(%g, %g)' % (p.x, p.y)I 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)

I 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

Page 330: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I 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

I You can pass an instance as an argument in the usual waydef print_point(p):

print '(%g, %g)' % (p.x, p.y)I 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)

I 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

Page 331: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I 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

I You can pass an instance as an argument in the usual waydef print_point(p):

print '(%g, %g)' % (p.x, p.y)I 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)

I 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

Page 332: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I 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

I You can pass an instance as an argument in the usual waydef print_point(p):

print '(%g, %g)' % (p.x, p.y)I 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)

I 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

Page 333: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 334: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 335: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 336: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 337: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 338: A 12 hour workshop on Introduction to Python

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))

I Sometimes it is obvious what the attributes of an object should be, but other times youhave to make decisions

I For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle?

I There are at least two possibilities:I specify one corner of the rectangle, the width, and the heightI specify two opposing corners

I Following the first one, here’s an example of the class definition. Corner represents thelower-left cornerclass Rectangle:

'''Represents a rectangle.attributes: width, height, corner.'''

Satyaki Sikdar© Programming in Python April 22 2016 106 / 137

Page 339: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I To represent a rectangle, you have to instantiate a Rectangle object and assign values tothe 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

I The expression box.corner.x means, “Go to the object box refers to and select theattribute named corner; then go to that object and select the attribute named x”

Satyaki Sikdar© Programming in Python April 22 2016 107 / 137

Page 340: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I To represent a rectangle, you have to instantiate a Rectangle object and assign values tothe 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

I The expression box.corner.x means, “Go to the object box refers to and select theattribute named corner; then go to that object and select the attribute named x”

Satyaki Sikdar© Programming in Python April 22 2016 107 / 137

Page 341: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I Functions can return instancesI 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.0p.y = rect.corner.y + rect.height / 2.0return p

>>> center = find_center(box)>>> print_point(center)(50.0, 100.0)

Satyaki Sikdar© Programming in Python April 22 2016 108 / 137

Page 342: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I Functions can return instancesI 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.0p.y = rect.corner.y + rect.height / 2.0return p

>>> center = find_center(box)>>> print_point(center)(50.0, 100.0)

Satyaki Sikdar© Programming in Python April 22 2016 108 / 137

Page 343: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I You can change the state of an object by making an assignment to one of its attributes

I You can also write functions that modify objects

def grow_rectangle(rect, dwidth, dheight):rect.width += dwidthrect.height += dheight

>>> print box.width100.0>>> print box.height200.0

>>> grow_rectangle(box, 50, 100)>>> print box.width150.0>>> print box.height300.0

Satyaki Sikdar© Programming in Python April 22 2016 109 / 137

Page 344: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I You can change the state of an object by making an assignment to one of its attributes

I You can also write functions that modify objects

def grow_rectangle(rect, dwidth, dheight):rect.width += dwidthrect.height += dheight

>>> print box.width100.0>>> print box.height200.0

>>> grow_rectangle(box, 50, 100)>>> print box.width150.0>>> print box.height300.0

Satyaki Sikdar© Programming in Python April 22 2016 109 / 137

Page 345: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I So far, the classes have been a little boring with just the definition and a docstring. Canwe 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)

I 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

Page 346: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I So far, the classes have been a little boring with just the definition and a docstring. Canwe 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)

I 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

Page 347: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I There’s no upper bound of the number of functions inside a class

I The first argument self is implicit, for exampleclass 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 += dxself.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

Page 348: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy manipulating objects

I There’s no upper bound of the number of functions inside a class

I The first argument self is implicit, for exampleclass 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 += dxself.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

Page 349: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the init method

I The init method is a special method that gets invoked when an object is createdI The full name is __init__, two underbars followed by init followed by two more

underbarsI The parameters for init usually have the same name as the attributesI The parameters here, are optional

#inside class Pointdef __init__(self, x=0.0, y=0.0):

self.x = xself.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

Page 350: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the init method

I The init method is a special method that gets invoked when an object is createdI The full name is __init__, two underbars followed by init followed by two more

underbarsI The parameters for init usually have the same name as the attributesI The parameters here, are optional

#inside class Pointdef __init__(self, x=0.0, y=0.0):

self.x = xself.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

Page 351: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the init method

I The init method is a special method that gets invoked when an object is createdI The full name is __init__, two underbars followed by init followed by two more

underbarsI The parameters for init usually have the same name as the attributesI The parameters here, are optional

#inside class Pointdef __init__(self, x=0.0, y=0.0):

self.x = xself.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

Page 352: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the init method

I The init method is a special method that gets invoked when an object is createdI The full name is __init__, two underbars followed by init followed by two more

underbarsI The parameters for init usually have the same name as the attributesI The parameters here, are optional

#inside class Pointdef __init__(self, x=0.0, y=0.0):

self.x = xself.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

Page 353: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the str method

I __str__ is a special method like __init__ and it’s supposed to return a stringrepresentation of the object

I Takes just the object as the argumentI For the Point class, the str method can be like

#inside the class Pointdef __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

Page 354: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the str method

I __str__ is a special method like __init__ and it’s supposed to return a stringrepresentation of the object

I Takes just the object as the argumentI For the Point class, the str method can be like

#inside the class Pointdef __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

Page 355: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the str method

I __str__ is a special method like __init__ and it’s supposed to return a stringrepresentation of the object

I Takes just the object as the argumentI For the Point class, the str method can be like

#inside the class Pointdef __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

Page 356: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the add method

I __add__ is a special method like __str__ and it overloads the ’+’ operator

I Takes two arguments, the caller object and another object. Returns a new object that’sthe sum of the two objects

I 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.xnew_pt.y = self.y + other_pt.yreturn new_pt

#outside the class>>> p1 = Point(2.0, 3.0) >>> print p1 + p2>>> p2 = Point(3.4, 8.2) (5.4, 11.2)

I Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137

Page 357: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the add method

I __add__ is a special method like __str__ and it overloads the ’+’ operator

I Takes two arguments, the caller object and another object. Returns a new object that’sthe sum of the two objects

I 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.xnew_pt.y = self.y + other_pt.yreturn new_pt

#outside the class>>> p1 = Point(2.0, 3.0) >>> print p1 + p2>>> p2 = Point(3.4, 8.2) (5.4, 11.2)

I Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137

Page 358: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the add method

I __add__ is a special method like __str__ and it overloads the ’+’ operator

I Takes two arguments, the caller object and another object. Returns a new object that’sthe sum of the two objects

I 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.xnew_pt.y = self.y + other_pt.yreturn new_pt

#outside the class>>> p1 = Point(2.0, 3.0) >>> print p1 + p2>>> p2 = Point(3.4, 8.2) (5.4, 11.2)

I Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137

Page 359: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy special methods

the add method

I __add__ is a special method like __str__ and it overloads the ’+’ operator

I Takes two arguments, the caller object and another object. Returns a new object that’sthe sum of the two objects

I 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.xnew_pt.y = self.y + other_pt.yreturn new_pt

#outside the class>>> p1 = Point(2.0, 3.0) >>> print p1 + p2>>> p2 = Point(3.4, 8.2) (5.4, 11.2)

I Other special methods incl __sub__, __lt__, __le__, __eq__, etc.Satyaki Sikdar© Programming in Python April 22 2016 114 / 137

Page 360: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 361: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 362: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 363: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 364: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 365: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

another example

I There are 52 cards in a deck. There are 4 suits - Spades, Hearts, Diamonds and Clubs

I Each suit has 13 cards - Ace, 2, ..., 10, Jack, Queen and King

I We’ll create a card class. Attributes can be strings, like ’Spade’ for suits and ’Queen’ forranks. We’ll have trouble comparing the cards

I We use integers to encode the ranks and suitsI Spades → 3, Hearts → 2, Diamonds → 1 and Clubs → 0I Ace → 1, Jack → 11, Queen → 12 and King → 13

Satyaki Sikdar© Programming in Python April 22 2016 115 / 137

Page 366: A 12 hour workshop on Introduction to Python

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 = suitself.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

Page 367: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

class and instance attributes

class attribute instance attributeDefined outside any method Defined inside methodsReferred by class.class_attr Referred by inst.inst_attr

One copy per class One copy per instanceEg: suit_names and rank_names Eg: suit and rank

Figure: Class and instance attributesSatyaki Sikdar© Programming in Python April 22 2016 117 / 137

Page 368: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 369: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 370: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 371: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 372: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 373: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 374: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

comparing cards

I For built-in types, there are relational operators (<,>,==, etc.) that compare two thingsto produce a boolean

I For user-defined types, we need to override the __cmp__ method. It takes in twoparameters, self and other, returns

I a positive number if the first object is greater

I a negative number if the second object is greater

I zero if they are equal

I The ordering for cards is not obvious. Which is better, the 3 of Clubs or the 2 ofDiamonds? One has a higher rank, but the other has a higher suit

I We arbitrarily choose that suit is more important, so all the Spades outrank all theDiamonds and so on.

Satyaki Sikdar© Programming in Python April 22 2016 118 / 137

Page 375: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

writing the __cmp__ method

#inside Card classdef __cmp__(self, other):

if self.suit > other.suit: #check the suitsreturn 1

elif self.suit < other.suit:return -1

elif self.rank > other.rank: #check the ranksreturn 1

elif self.rank < other.rank:return -1

else: #both the suits and the ranks are the samereturn 0

Satyaki Sikdar© Programming in Python April 22 2016 119 / 137

Page 376: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

decks

I Now that we have Cards, we define Decks. It will contain a list of Cards

I 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

Page 377: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

decks

I Now that we have Cards, we define Decks. It will contain a list of Cards

I 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

Page 378: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy an elaborate example

decks

#inside class Deckdef __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 Deckdef 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

Page 379: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 380: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 381: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 382: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 383: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 384: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

inheritance

I The language feature most often associated with object-oriented programming isinheritance

I It’s the ability to define a new class that’s a modified version of an existing class

I The existing class is called the parent and the new class is called the child

I We want a class to represent a hand that is, the set of cards held by a player

I A hand is similar to a deck: both are made up of a set of cards, and both requireoperations like adding and removing cards

I A hand is also different from a deck; there are operations we want for hands that don’tmake sense for a deck

Satyaki Sikdar© Programming in Python April 22 2016 122 / 137

Page 385: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I The definition of a child class is like other class definitions, but the name of the parentclass appears in parenthesesclass Hand(Deck):

'''Represents a hand of playing cards'''

I This definition indicates that Hand inherits from Deck; that means we can use methodslike pop_card and add_card for Hands as well as Decks

I Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the initmethod for Hands should initialize cards with an empty list

I 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

Page 386: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I The definition of a child class is like other class definitions, but the name of the parentclass appears in parenthesesclass Hand(Deck):

'''Represents a hand of playing cards'''

I This definition indicates that Hand inherits from Deck; that means we can use methodslike pop_card and add_card for Hands as well as Decks

I Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the initmethod for Hands should initialize cards with an empty list

I 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

Page 387: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I The definition of a child class is like other class definitions, but the name of the parentclass appears in parenthesesclass Hand(Deck):

'''Represents a hand of playing cards'''

I This definition indicates that Hand inherits from Deck; that means we can use methodslike pop_card and add_card for Hands as well as Decks

I Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the initmethod for Hands should initialize cards with an empty list

I 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

Page 388: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I The definition of a child class is like other class definitions, but the name of the parentclass appears in parenthesesclass Hand(Deck):

'''Represents a hand of playing cards'''

I This definition indicates that Hand inherits from Deck; that means we can use methodslike pop_card and add_card for Hands as well as Decks

I Hand also inherits __init__ from Deck, but it doesn’t really do what we want: the initmethod for Hands should initialize cards with an empty list

I 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

Page 389: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I So when you create a Hand,Python invokes it’s own init

>>> hand = Hand('new hand')>>> print hand.cards[]>>> print hand.labelnew hand

I 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 HandKing of Spades

I A natural next step is to encapsulate this code in a method called move_cards

#inside class Deckdef move_cards(self, hand, card):

for i in xrange(num):hand.add_card(self.pop_card())

I 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

Page 390: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I So when you create a Hand,Python invokes it’s own init

>>> hand = Hand('new hand')>>> print hand.cards[]>>> print hand.labelnew hand

I 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 HandKing of Spades

I A natural next step is to encapsulate this code in a method called move_cards

#inside class Deckdef move_cards(self, hand, card):

for i in xrange(num):hand.add_card(self.pop_card())

I 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

Page 391: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I So when you create a Hand,Python invokes it’s own init

>>> hand = Hand('new hand')>>> print hand.cards[]>>> print hand.labelnew hand

I 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 HandKing of Spades

I A natural next step is to encapsulate this code in a method called move_cards

#inside class Deckdef move_cards(self, hand, card):

for i in xrange(num):hand.add_card(self.pop_card())

I 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

Page 392: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

I So when you create a Hand,Python invokes it’s own init

>>> hand = Hand('new hand')>>> print hand.cards[]>>> print hand.labelnew hand

I 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 HandKing of Spades

I A natural next step is to encapsulate this code in a method called move_cards

#inside class Deckdef move_cards(self, hand, card):

for i in xrange(num):hand.add_card(self.pop_card())

I 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

Page 393: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy inheritance

#inside class Deckdef deal_hands(self, num_hands, cards_per_hand):

hands = []self.shuffle() #shuffling the deckfor 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

I 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

Page 394: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

the need for file handling

I Most of the programs we have seen so far are transient in the sense that they run for ashort time and produce some output, but when they end, their data disappears. If you runthe program again, it starts with a clean slate

I Other programs are persistent: they run for a long time (or all the time); they keep atleast some of their data in permanent storage (a hard drive, for example); if they shutdown and restart, they pick up where they left off

I Big input and output sizes - too big for the main memory

Satyaki Sikdar© Programming in Python April 22 2016 126 / 137

Page 395: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

the need for file handling

I Most of the programs we have seen so far are transient in the sense that they run for ashort time and produce some output, but when they end, their data disappears. If you runthe program again, it starts with a clean slate

I Other programs are persistent: they run for a long time (or all the time); they keep atleast some of their data in permanent storage (a hard drive, for example); if they shutdown and restart, they pick up where they left off

I Big input and output sizes - too big for the main memory

Satyaki Sikdar© Programming in Python April 22 2016 126 / 137

Page 396: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

the need for file handling

I Most of the programs we have seen so far are transient in the sense that they run for ashort time and produce some output, but when they end, their data disappears. If you runthe program again, it starts with a clean slate

I Other programs are persistent: they run for a long time (or all the time); they keep atleast some of their data in permanent storage (a hard drive, for example); if they shutdown and restart, they pick up where they left off

I Big input and output sizes - too big for the main memory

Satyaki Sikdar© Programming in Python April 22 2016 126 / 137

Page 397: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

I Examples of persistent programs are operating systems, which run pretty much whenever acomputer is on, and web servers, which run all the time, waiting for requests to come in onthe network.

I One of the simplest ways for programs to maintain their data is by reading and writingtext files.

fp_read = open('input.txt', 'r')fp_write = open('output.txt', 'w')

Satyaki Sikdar© Programming in Python April 22 2016 127 / 137

Page 398: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

I Examples of persistent programs are operating systems, which run pretty much whenever acomputer is on, and web servers, which run all the time, waiting for requests to come in onthe network.

I One of the simplest ways for programs to maintain their data is by reading and writingtext files.

fp_read = open('input.txt', 'r')fp_write = open('output.txt', 'w')

Satyaki Sikdar© Programming in Python April 22 2016 127 / 137

Page 399: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

reading from files

I The built-in function open takes the name of the file as a parameter and returns a fileobject you can use to read the file>>> fin = open('input.txt', 'r')>>> print fin>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>

I A few things to note: The file opened must exist. An IOError is thrown otherwise.I 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

Page 400: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

reading from files

I The built-in function open takes the name of the file as a parameter and returns a fileobject you can use to read the file>>> fin = open('input.txt', 'r')>>> print fin>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>

I A few things to note: The file opened must exist. An IOError is thrown otherwise.I 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

Page 401: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

reading from files

I The built-in function open takes the name of the file as a parameter and returns a fileobject you can use to read the file>>> fin = open('input.txt', 'r')>>> print fin>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>

I A few things to note: The file opened must exist. An IOError is thrown otherwise.I 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

Page 402: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

reading from files

I The built-in function open takes the name of the file as a parameter and returns a fileobject you can use to read the file>>> fin = open('input.txt', 'r')>>> print fin>>> <open file 'input.txt', mode 'r' at 0xb7eb2410>

I A few things to note: The file opened must exist. An IOError is thrown otherwise.I 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

Page 403: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy file handling 101

reading files

I The file object provides several methods for reading, including readline, which readscharacters 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

Page 404: A 12 hour workshop on Introduction to Python

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>

I 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,\n'>>> fout.write(line1)

Again, the file object keeps track of where it is, so if you call write again, it adds the newdata 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

Page 405: A 12 hour workshop on Introduction to Python

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 stringdef 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_valuesreturn counter

Satyaki Sikdar© Programming in Python April 22 2016 131 / 137

Page 406: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 407: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 408: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 409: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 410: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 411: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy algorithms in Python

algorithm design in Python

I One of the strong points of Python is the ease of expression

I Turning pseudocode into actual code is not difficult

I Let’s try to implement the Merge Sort algorithm in Python

A high level idea of the algorithm

I Divide: Divide the n-element sequence into two subsequences of n2 elements

I Conquer: Sort the subsequences recursively

I Combine: Merge the two sorted subsequences to produce the sorted answer

Satyaki Sikdar© Programming in Python April 22 2016 132 / 137

Page 412: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

Algorithm 1: MERGE(left, right)

beginAppend ∞ to left and righti← 0, j ← 0merged← new listwhile len(merged) < len(left) + len(right) do

if left[i] < right[j] thenmerged.append(left[i])i← i+ 1

elsemerged.append(right[j])j ← j + 1

return merged

Algorithm 2: MERGE-SORT(A)

beginif len(A) < 2 then

return A

elseleft← first n

2 elements of Aright← last n

2 elements of Aleft←MERGE − SORT (left)right←MERGE − SORT (right)

return MERGE(left, right)

Satyaki Sikdar© Programming in Python April 22 2016 133 / 137

Page 413: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

the core idea

I The algorithm is naturally recursive

I The MERGE method takes two sorted lists and merges into a single sorted list

I MERGE − SORT sorts the list recursively by breaking it into equal sized halves andsorting them

I A list having less than 2 elements is trivially sorted - base case

I Smaller sorted lists are agglomerated to form the overall sorted list

Satyaki Sikdar© Programming in Python April 22 2016 134 / 137

Page 414: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

the core idea

I The algorithm is naturally recursive

I The MERGE method takes two sorted lists and merges into a single sorted list

I MERGE − SORT sorts the list recursively by breaking it into equal sized halves andsorting them

I A list having less than 2 elements is trivially sorted - base case

I Smaller sorted lists are agglomerated to form the overall sorted list

Satyaki Sikdar© Programming in Python April 22 2016 134 / 137

Page 415: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

the core idea

I The algorithm is naturally recursive

I The MERGE method takes two sorted lists and merges into a single sorted list

I MERGE − SORT sorts the list recursively by breaking it into equal sized halves andsorting them

I A list having less than 2 elements is trivially sorted - base case

I Smaller sorted lists are agglomerated to form the overall sorted list

Satyaki Sikdar© Programming in Python April 22 2016 134 / 137

Page 416: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

the core idea

I The algorithm is naturally recursive

I The MERGE method takes two sorted lists and merges into a single sorted list

I MERGE − SORT sorts the list recursively by breaking it into equal sized halves andsorting them

I A list having less than 2 elements is trivially sorted - base case

I Smaller sorted lists are agglomerated to form the overall sorted list

Satyaki Sikdar© Programming in Python April 22 2016 134 / 137

Page 417: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy the pseudocode

the core idea

I The algorithm is naturally recursive

I The MERGE method takes two sorted lists and merges into a single sorted list

I MERGE − SORT sorts the list recursively by breaking it into equal sized halves andsorting them

I A list having less than 2 elements is trivially sorted - base case

I Smaller sorted lists are agglomerated to form the overall sorted list

Satyaki Sikdar© Programming in Python April 22 2016 134 / 137

Page 418: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy implementation

Algorithm 3: MERGE(left, right)

beginAppend ∞ to left and righti← 0, j ← 0merged← new listwhile len(merged) < len(left) + len(right) do

if left[i] < right[j] thenmerged.append(left[i])i← i+ 1

elsemerged.append(right[j])j ← j + 1

return merged

def merge(left, right):left.append(float('inf'))right.append(float('inf'))i = 0j = 0merged = []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

Page 419: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy implementation

Algorithm 4: MERGE-SORT(A)

beginif len(A) < 2 then

return A

elseleft← first n

2 elements of Aright← last n

2 elements of Aleft←MERGE − SORT (left)right←MERGE − SORT (right)return MERGE(left, right)

def merge_sort(A):if len(A) < 2:

return Aelse:

mid = len(A) / 2left = 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

Page 420: A 12 hour workshop on Introduction to Python

hour 5: oops-a-daisy implementation

That’s all for today! Hope you had fun! Make sure you have a workingnetworkx setup for tomorrow...

Satyaki Sikdar© Programming in Python April 22 2016 137 / 137