Python-Programming-Modular-Approach (Sheetal Taneja and Naveen Kumar)
Python-Programming-Modular-Approach (Sheetal Taneja and Naveen Kumar)
Sh eet a l T a n eja
Department of Computer Science
Dyal Singh College
Univers ity of Delhi
Delhi, India
and
Na v een Ku m a r
Department of Computer Science
Univers ity of Delhi
Delhi, India
Contents
Forew ord
Preface
1 . Py th on Pr og r a m m in g : A n In tr odu ction
1 .2 Py th on Str in g s
As s ignment Statement
Shorthand Notation
1 .7 Key w or ds
Summary
Exercis es
2 . Fu n ction s
2 .1 Bu ilt-in Fu n ction s
input Function
eval Function
Composition
print Function
type Function
round Function
pow Function
Function help
2 .5 Com m a n d Lin e A r g u m en ts
Summary
Exercis es
3 .2 .1 for Loop
3 .2 .2 while Loop
Infinite Loops
3 .2 .5 Nested Loops
Summary
Exercis es
4 . Debu g g in g
4 .1 Testin g
An Example: Finding Maximum of Three Numbers
4 .2 Debu g g in g
Summary
Exercis es
5 . Scope
5 .2 Scope of Objects a n d Na m es
5 .2 .1 Na m espa ces
5 .2 .2 Scope
LEGB Rule
Summary
Exercis es
6 . Str in g s
6 .1 Str in g s
6 .1 .1 Slicin g
6 .1 .2 Mem ber sh ip
Function count
Function replace
Function join
Lis t of Functions
Summary
Exercis es
7 .1 Lists
7 .1 .2 Fu n ction list
7 .1 .4 Fu n ction insert
7 .1 .5 Fu n ction reverse
7 .1 .7 List Fu n ction s
7 .1 .9 Lists a s A r g u m en ts
7 .2 Sets
7 .2 .3 Fu n ction copy
7 .2 .5 List of Fu n ction s
7 .3 Tu ples
7 .4 Diction a r y
7 .4 .2 Deletion
7 .4 .3 Fu n ction get
7 .4 .4 Fu n ction update
7 .4 .5 Fu n ction copy
7 .4 .6 List of Fu n ction s
7 .4 .7 In v er ted Diction a r y
Summary
Exercis es
8 . Recu r sion
8 .1 .1 Fa ctor ia l
Iterative Approach
Iterative Approach
8 .2 .1 Len g th of a Str in g
8 .2 .3 Pa lin dr om e
8 .3 .2 Copy
8 .3 .3 Deep Copy
8 .3 .4 Per m u ta tion
8 .4 Pr oblem of Tow er of Ha n oi
Summary
Exercis es
9 . Files a n d Ex ception s
9 .1 File Ha n dlin g
9 .3 Er r or s a n d Ex ception s
Summary
Exercis es
1 0. Cla sses I
1 0.4 Da te Cla ss
Summary
Exercis es
1 1 . Cla sses II
1 1 .1 Poly m or ph ism
Comparing Dates
1 1 .6 Com position
1 1 .7 In h er ita n ce
1 1 .7 .1 Sin g le In h er ita n ce
Scope Rule
1 1 .7 .3 Mu ltiple In h er ita n ce
Summary
Exercis es
1 2 .1 Sor tin g
1 2 .1 .1 Selection Sor t
1 2 .1 .2 Bu bble Sor t
1 2 .2 .1 Lin ea r Sea r ch
1 2 .2 .2 Bin a r y Sea r ch
1 2 .3 A Ca se Stu dy
Complete Script
1 2 .4 .1 Mer g e Sor t
1 2 .4 .2 Qu ick Sor t
Summary
Exercis es
1 3 .1 Sta cks
1 3 .2 Qu eu es
Summary
Exercis es
1 4 .1 In tr odu ction
Summary
Exercis es
1 5 .2 Bin a r y Sea r ch Tr ee
1 5 .3 .1 In or der Tr a v er sa l
1 5 .3 .2 Pr eor der Tr a v er sa l
1 5 .3 .3 Postor der Tr a v er sa l
1 5 .3 .4 Heig h t of a Bin a r y Tr ee
Summary
Exercis es
1 6 .6 Su doku
Summary
Exercis es
1 7 . Gr a ph ics
1 7 .1 2 D Gr a ph ics
1 7 .1 .1 Poin t a n d Lin e
Multiple Plots
Saving Figure
1 7 .1 .2 Histog r a m a n d Pi Ch a r t
1 7 .1 .3 Sin e a n d Cosin e Cu r v es
Circle
Ellips e
Rectangle
Polygon
Arrow
1 7 .2 3 D Objects
Box
Sphere
Ring
Cylinder
Arrow
Cone
Curve
Summary
Exercis es
1 8 . A pplica tion s of Py th on
Open Authentication
1 8 .2 Sh a r in g Da ta Usin g Sockets
An Echo Server
1 8 .3 .1 Da ta ba se Con cepts
1 8 .3 .2 Cr ea tin g Da ta ba se a n d Ta bles
1 8 .4 .2 Tic-Ta c-Toe Ga m e
1 8 .5 .1 A ccessin g Ja v a Collection s a n d A r r a y s in Py th on
Summary
Exercis es
Index
Pr of. S K Gu pt a
Department of Computer Science and Engineering
Indian Ins titute of Technology Delhi
New Delhi, India
Preface
ACKNOWLEDGEMENTS
Sh eet a l T a n eja
Na v een Ku m a r
About the Authors
CHAPTER OUTLINE
1 .1 IDLE – A n In ter pr eter for Py th on
1 .2 Py th on Str in g s
1 .7 Key w or ds
hello world
>>> 18 + 5
23
Py th on sh ell w in dow
>>> 3 ** 2
>>> 6 / 3 / 2
1.0
>>> 2 ** 3 ** 2
512
>>> 10 * -5
-50
>>> 7 + 3(4 + 5)
7 + 3(4 + 5)
>>> 7 / 0
'Hello World'
Hello World
>>> """Hello
What's
happening"""
"Hello\nWhat's\nhappening"
>>> print("""Hello
What's
happening""")
Hello
What's
happening
'hello !!'
'hellohellohellohellohello'
log ica l oper a tor s not, and, or y ield v a lu es: True, False
False
i.e. False
>> english = 57
a v a r ia ble is a n a m e g iv en to a v a lu e
>>> english
57
>>> maths = 64
>>> commerce = 62
>>> percentage
61.0
variable = expression
total_marks
TotalMarks
totalMarks
TOTAL_MARKS
a lw a y s u se m ea n in g fu l v a r ia ble n a m es
>>> age = 24
>>> Age
Age
>>> a = 5
>>> b = a
>>> a = 7
Shorthand Notation
>> a = a + 5
>>> a += 5
a sh or th a n d n ota tion
>>> a = a + b + c
>>> a = a ** (b + c)
>>> a += b + c
>>> a **= b + c
a = a <operator> b
is equivalent to
a <operator>= b
>>> totalMarks = 0
>>> count = 0
20 10
Note that before executing the assignment statement
num1 = num2
1.7 KEYWORDS
key w or ds h a v e specia l m ea n in g
SUMMARY
1 0. A v a r ia ble is a n a m e th a t r efer s to a v a lu e. We m a y
a lso sa y th a t a v a r ia ble a ssocia tes a n a m e w ith a da ta
object su ch a s n u m ber , ch a r a cter , str in g , or Boolea n .
1 1 . V a lu es a r e a ssig n ed to v a r ia bles u sin g a ssig n m en t
sta tem en t. Th e sy n ta x for a ssig n m en t sta tem en t is a s
follow s:
variable = expression
w h er e ex pr ession m a y y ield a n y v a lu e su ch a s
n u m er ic, str in g , or Boolea n .
1 2 . In a n a ssig n m en t sta tem en t, th e expression on th e
right-hand s ide of th e equ a l to oper a tor (=) is ev a lu a ted
a n d th e v a lu e so obta in ed is a ssig n ed to th e v a r ia ble on
th e left-hand s ide of th e = oper a tor .
1 3 . A v a r ia ble n a m e m u st beg in w ith a letter or _
(u n der scor e ch a r a cter ). It m a y con ta in a n y n u m ber of
letter s, dig its or u n der scor e ch a r a cter s. No oth er
ch a r a cter a pa r t fr om th ese is a llow ed.
1 4 . Py th on is ca se-sen sitiv e. Th u s, age a n d Age a r e
differ en t v a r ia bles.
1 5 . Th e sh or th a n d n ota tion for a = a <operator> b is
a <operator>= b
1 6 . In Py th on , m u ltiple a ssig n m en t sta tem en ts ca n be
specified in a sin g le lin e a s follow s:
<name1>, <name2>, ... = <expression1>,
<expression2>, ...
1 7 . A key w or d is a r eser v ed w or d th a t is a lr ea dy defin ed by
Py th on for a specific u se. Key w or ds ca n n ot be u sed for
a n y oth er pu r pose. Th e list of th e Py th on key w or ds is
g iv en below :
in raise elif
EXERCISES
1 . Ev a lu a te th e follow in g ex pr ession s:
(x < y) or (not(z == y) and (z < x))
1 . x = 0, y = 6 , z = 1 0
2. x = 1, y = 1, z = 1
2 . Ev a lu a te th e follow in g ex pr ession s in v olv in g
a r ith m etic oper a tor s:
1 . -7 * 20 + 8 / 16 * 2 + 54
2 . 7 ** 2 // 9 % 3
3 . ( 7 – 4 * 2 ) * 10 / 5 ** 2 + 15
4 . 5 % 10 + 10 – 25 * 8 // 5
5 . ' hello' * 2 - 5
3 . Ev a lu a te th e follow in g ex pr ession s in v olv in g r ela tion a l
a n d log ica l oper a tor s:
1 . 'hi' > 'hello' and 'bye' < 'Bye'
2 . 'hi' > 'hello' or 'bye' < 'Bye'
3 . 7 > 8 or 5 < 6 and 'I am fine' > 'I am
not fine'
4 . 10 != 9 and 29 >= 29
5 . 10 != 9 and 29 >= 29 and 'hi' > 'hello'
or 'bye' < 'Bye' and 7 <= 2.5
4 . Ev a lu a te th e follow in g ex pr ession s in v olv in g
a r ith m etic, r ela tion a l, a n d log ica l oper a tor s:
1 . 5 % 10 + 10 < 50 and 29 >= 29
2 . 7 ** 2 <= 5 // 9 % 3 or 'bye' < 'Bye'
3 . 5 % 10 < 10 and – 25 > 1 * 8 // 5
4 . 7 ** 2 // 4 + 5 > 8 or 5 != 6
5 . 7 / 4 < 6 and 'I am fine' > 'I am not
fine'
6 . 10 + 6 * 2 ** 2 != 9 // 4 - 3 and 29 >=
29 / 9
7 . 'hello' * 5 > 'hello' or 'bye' < 'Bye'
5 . Ev a lu a te th e follow in g ex pr ession s in v olv in g bitw ise
oper a tor s:
1 . 15 & 22
2 . 15 | 22
3 . -15 & 22
4 . -15 | 22
5 . ~15
6 . ~22
7 . ~-20
8 . 15 ^ 22
9 . 8 << 3
1 0. 40 >> 3
6 . Differ en tia te betw een th e follow in g oper a tor s w ith th e
h elp of ex a m ples:
1 . = a n d ==
2. / and %
3 . / a n d //
4 . * a n d **
7 . Wh a t ou tpu t w ill be displa y ed w h en th e follow in g
com m a n ds a r e ex ecu ted in Py th on sh ell in sequ en ce:
1 . >>> a = 6
>>> a == 6
>>> a < 5.9
>>> a > 5.9
2 . >>> b = 7
>>> b / 6
>>> b // 6
>>> b / 4
>>> b % 4
>>> b % 7
>>> b * 2
>>> b ** 2
8 . Con str u ct log ica l ex pr ession s for r epr esen tin g th e
follow in g con dition s:
1 . marks scor ed sh ou ld be g r ea ter th a n 300 a n d less
th a n 400.
2 . Wh eth er th e v a lu e of grade is a n u pper ca se
letter .
3 . Th e post is engineer a n d experience is m or e
th a n fou r y ea r s.
9 . Iden tify Py th on key w or ds fr om th e follow in g list of
w or ds:
1.
2.
3.
CHAPTER OUTLINE
2 .1 Bu ilt-in Fu n ction s
2 .5 Com m a n d Lin e A r g u m en ts
input Function
>>> name
'Alok'
eval Function
The function eval is used to evaluate the value of a
string, for example:
ev a lu a tin g a str in g
>>> eval('15')
15
>>> eval('15+10')
25
Composition
>>> n1
234
>>> n2
38.0
print Function
print('hello')
>>> print('hello')
hello
2 567 234
hello Raman 2 + 2 = 4
Note that when several values are included in a call to
the print function separated by commas, they are
displayed on the same line, separated by single spaces
between them. It is important to point out that after
printing the values of the expressions included as
arguments while invoking the print function, the print
control moves to the beginning of the next line. Thus,
the output of a sequence of print function calls appears
on separate lines. In the next example, the output of a
single call to the print function is displayed on two
lines:
hello Raman
2 + 2 = 4
hello Raman 2 + 2 = 4
type Function
deter m in in g da ta ty pe
<class 'type'>
round Function
r ou n din g to n ea r est v a lu e
>>> print(round(89.625,2), round(89.635),
round(89.635,0))
89.62 90 90.0
34.1 -35
Type Conversion
Enter profit: 5
Selling Price: 505
Enter profit: 5
Selling Price: 55
>>> str(123)
'123'
>>> float(123)
123.0
>>> int(123.0)
123
>>> str(123.45)
'123.45'
>>> float('123.45')
123.45
>>> int('123.45')
int('123.45')
>>> eval('50+5')
55
95.6
59
'you'
'Sir'
pow Function
b
The function pow(a, b)computes a . Thus, given the
side of a cube, if we want to find its volume, we may
just write pow(side, 3).
import random
else:
import math
>>> math.ceil(3.4)
>>> math.floor(3.7)
>>> math.fabs(-3)
3.0
>>> math.exp(2)
7.38905609893065
>>> math.log(32, 2)
5.0
>>> math.log10(100)
2.0
>>> math.pow(3, 3)
27.0
>>> math.sqrt(65)
8.06225774829855
>>> math.cos(math.pi)
-1.0
>>> math.sin(math.pi/2)
1.0
>>> math.tan(math.pi/4)
0.9999999999999999
>>> math.acos(1)
0.0
>>> math.asin(1)
1.5707963267948966
>>> math.atan(1)
0.7853981633974483
>>> math.degrees(math.pi)
180.0
>>> math.radians(180)
3.141592653589793
>>> help(math.cos)
cos(...)
cos(x)
print a triangle
print a square
m u lti-lin e com m en t
def function_name
(comma_separated_list_of_parameters):
statements
if __name__=='__main__':
main()
square
areaRectangle:
output: area
computations:
a r g u m en ts m u st a ppea r in th e sa m e or der a s th a t of
pa r a m eter s
Fig. 2.9 Pr og r a m to fin d a r ea of a r ecta n g le (area.py)
Area of rectangle is 20
End of program
areaRectangle(side, side)
u se of fu n ction areaRectangle for com pu tin g a r ea of th e
squ a r e
Function help
>>> help(areaRectangle)
areaRectangle(length, breadth)
>>> areaRectangle(5)
10
Keyword Arguments
parameter_name = value
sy n ta x for key w or d a r g u m en ts
areaRect = areaRectangle(breadth = 2,
length = 5)
return a + b + c + d + e + f + g + h
62
specify in g sy stem pa th
import name-of-the-module
Length: 500
Width: 400
200000
assert condition
Fig. 2.15 Pr og r a m to fin d per cen ta g e (percent.py)
File "F:/PythonCode/Ch02/percent.py",
line 25,
in <module>
main()
File "F:/PythonCode/Ch02/percent.py",
line 20,
in main
AssertionError
!
2.5 COMMAND LINE ARGUMENTS
F:\PythonCode\Ch02>python area.py
End of program
F:\PythonCode\Ch02>python area1.py 20 10
End of program
python area1.py 20 10
SUMMARY
EXERCISES
math.fabs(-67.58) math.fabs(3)
math.exp(2.7) math.log(45,2)
math.log10(1000) math.pow(4,1/2)
math.sqrt(121) math.radians(30)
math.degrees(math.pi/2)
1.
2.
F ig . 2.18 (mainModule.py)
CHAPTER OUTLINE
3 .1 if Con dition a l Sta tem en t
>>>
Enter marks: 38
Moderated marks: 40
>>>
Enter marks: 39
Moderated marks: 40
>>>
Enter marks: 40
Moderated marks: 40
In Fig. 3.2, we give a representation of the function
moderate using a flowchart.
LOGIN SYSTEM
==============================
Password mismatch !!
LOGIN SYSTEM
==============================
Login Successful !!
Welcome to system.
Conditional Expression
if password == 'magic':
else:
message = ' Password mismatch !!\n '
may be replaced by
else:
else:
to fin d m a x im u m of th r ee n u m ber s
Fig. 3.12 Pr og r a m to fin d th e m a x im u m of th r ee n u m ber s
(maximum.py)
>>>
range(1,11) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
range(11) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
range(1,11,2) 1, 3, 5, 7, 9
total += count
Enter marks
Subject 1: 75
Subject 2: 80
Subject 3: 85
Subject 4: 90
Subject 5: 95
<block S of statements>
for loop sy n ta x
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40
>>> print(7)
>>> print(100)
100
>>> '%5d'% 45
' 45'
45
>>> print('%5d'% 12345)
12345
>>>
Enter a number: 2
Enter a number: 18
Enter a number: 15
Enter a number: 15
Enter a number:
Infinite Loops
import time
while True:
try:
print('Loop processing....')
time.sleep(1)
except KeyboardInterrupt:
break
total += count
count = 1
while count < n+1:
total += count
count += 1
print('*' * i)
nSpaces = 0
nStars = 2 * nRows - 1
We also note that the number of stars to be printed
decreases by two for every subsequent row. With these
remarks, we modify the outline of the above piece of
code as follows:
nSpaces = 0
nStars = 2 * nRows - 1
nStars -= 2
nSpaces += 1
print('{0: >5}'.format(i*9))
18
27
9 18 27
print('{0: >5}'.format(i*9))
is equivalent to:
print('{0: >2}'.format(num),'*',\
'{0: >2}'.format(multiple),'=', \
'{0: >3}'.format(num*multiple),'\t',
end = '')
print()
INVALID MARKS !!
INVALID MARKS !!
Number of Subjects: 4
Percentage: 72.5
x/1
2 3
x/1*(-x )/(2*3) = -x /3!
3 2 5
-x /3!*(-x )/(4*5) = x /5!
2
2
To code the above idea, we set multBy equal to -x and
initialize nxtInSeq (used to compute divBy) equal to
2. We compute divBy = nxtInSeq*(nxtInSeq+1).
Every time we compute a new term, we increment the
value of nxtInSeq by 2. Table 3.1 illustrates these
computations:
while <test-condition>:
<Sequence S of statements>
EXERCISES
2.
1 2 1.5 −1 2 0.25
CHAPTER OUTLINE
4 .1 Testin g
4 .2 Debu g g in g
debu g g in g : m a kin g th e pr og r a m er r or fr ee
4.1 TESTING
1. 30, 20, 10
2. 30, 10, 20
3. 20, 10, 30
4. 20, 30, 10
5. 10, 30, 20
6. 10, 20, 30
Fig. 4.1 Pr og r a m to fin d th e m a x im u m of th r ee n u m ber s
(max3.py)
>>>
Maximum number is 0
4.2 DEBUGGING
There are various Python debugging tools such as pdb,
pudb, pydb, and pydbgr. In this section, we will discuss
Python's built-in debugger pdb, which is an interactive
tool that helps in examining the code execution step by
step. It allows us to stop the execution of a program at a
chosen instruction called a break point, and evaluate the
various expressions in the current context. The debugger
also allows us to examine the current vicinity of the
code, as well as the status of various objects in the
current function being executed which collectively
constitute the stack frame corresponding to that
function.
pdb: py th on debu g g er
>>> pdb.run('max3.main()')
> <string>(1)<module>()->None
(Pdb)
import pdb
pdb.set_trace()
def main():
u: m ov e on e lev el u p in th e sta ck fr a m e
f:\pythoncode\ch04\max3.py(32)<module>()-
>None
q: qu it th e debu g g er
n1 = 20
n2 = 10
n3 = 30
b: set th e br ea kpoin t
SUMMARY
Pr i nt s t h e st ac k t r ac e (sequ enc e of f u nc t i on c al l s
w or c u r r ent l y i n ex ec u t i on, most r ec ent f u nc t i on c al l
where b ei ng at t h e b egi nni ng). A l so sh ow s t h e st at ement t o b e
ex ec u t ed nex t .
r or
Cont i nu e ex ec u t i on u nt i l t h e c u r r ent f u nc t i on
retur
r et u r ns.
n
j(ump
) Ju mp s t o t h e gi v en l i ne nu mb er f or t h e nex t st at ement
linen t o b e ex ec u t ed.
o
l or
Li st 1 1 l i nes i n t h e v i c i ni t y of t h e c u r r ent st at ement .
list
b or
Set s t h e b r eak p oi nt at t h e l i ne sp ec i f i ed (name of f i l e
break
op t i onal ). If t h e ar gu ment func sp ec i f y i ng f u nc t i on
[[fil
name i s p r ov i ded, b r eak p oi nt i s set at t h e f i r st
e:]li
ex ec u t ab l e st at ement of t h e f u nc t i on. Th e sec ond
ne|fu
ar gu ment may b e u sed t o denot e a c ondi t i on w h i c h
nc[,c
mu st ev al u at e t o True f or set t i ng t h e b r eak p oi nt .
ond]]
tbrea
k
[[fil Si mi l ar t o break c ommand. How ev er , b r eak p oi nt s
e:]li b ei ng set ar e au t omat i c al l y r emov ed onc e t h ey ar e
ne|fu r eac h ed.
nc[,c
ond]]
c or
conti Cont i nu e ex ec u t i on u nt i l t h e b r eak p oi nt i s r eac h ed.
nue
p or
print
Pr i nt s t h e v al u e of t h e sp ec i f i ed ex p r essi on i n t h e
(expr
c u r r ent c ont ex t .
essio
n)
q or
Qu i t s f r om t h e Py t h on deb u gger .
quit
EXERCISES
CHAPTER OUTLINE
5 .1 Objects a n d Object IDs
5 .2 Scope of Objects a n d Na m es
a = 5 id(a): 10538176
b = 5 id(b): 10538176
a = 7 id(a): 10538240
b = 5 id(b): 10538176
b = 3 + 2
http://www.pythontutor.com/visualize.html#mode=
display
sh a r ed session
Once we have learned to use the visualizer, we can play
with other options. Finally, to visualize the execution of
code, we click the icon Visualize Execution, and a bar
showing the progress of program execution appears.
Clicking somewhere on this bar would execute a fraction
of the code. Alternatively, we can use the forward and
back buttons. To begin with, we prefer the latter option.
Anytime, we want to modify the code, we can click on
Edit code.
>>> print(id(2.4))
46078432
>>> print(id(2.4))
47619216
>>> print(id(2.4))
47619024
>>> print(id(2.4))
46078432
>>> print(id(2.4))
47619024
>>> print(id(2.4))
47619216
>>> a = 5
>>> b = 5
10538176 10538176
>>> del a
>>> print(a)
File "<pyshell#26>", line 1, in <module>
print(a)
>>> print(b)
>>> del b
>>> print(b)
print(b)
del a
is executed, it reduces the reference count of int object
5 from 2 to 1 and removes the binding of name a to int
object 5 as shown in Fig. 5.9. Therefore, an attempt to
access a now yields an error. However, the name b
continues to refer to int object 5 created on execution of
the statement
b = 5
del b
Fig. 5.9 V isu a liza tion in Py th on tu tor
Fig. 5.10 V isu a liza tion in Py th on tu tor
Step 1 of 5
<In pu t Box>
5.2.1 Namespaces
5.2.2 Scope
LEGB Rule
Example 5.1
global a: 4
Example 5.2
local a: 5
global a: 4.2
Example 5.3
inside function g, b: 5
Example 5.4
in outer function g, a =
File "F:/PythonCode/Ch05/scope4.py",
line 6, in <module>
f()
File "F:/PythonCode/Ch05/scope4.py",
line 5,
in f
Example 5.5
File "F:/PythonCode/Ch05/scope5.py",
line 9,
in <module>
f()
File "F:/PythonCode/Ch05/scope5.py",
line 8,
in f
g()
File "F:/PythonCode/Ch05/scope5.py",
line 5,
in g
b = a
Example 5.6
after calling f, a = 4
Example 5.7
Example 5.8
>>>
global f
inner f
global f
inside h: id(f): 40686704
inner f
File "F:/PythonCode/Ch05/scope8.py",
line 27,
in <module>
main()
File "F:/PythonCode/Ch05/scope8.py",
line 24,
in main
h()
File "F:/PythonCode/Ch05/scope8.py",
line 15,
in h
fprime()
SUMMARY
EXERCISES
CHAPTER OUTLINE
6 .1 Str in g s
6 .3 Pa tter n Ma tch in g
6.1 STRINGS
>>> len(message)
10
Individual characters within a string are accessed using
a technique known as indexing. In Fig. 6.1, we illustrate
the notion of indexing with the help of the string 'Hello
Gita'.
>>> message[0]
'H'
>>> message[6]
'G'
'a'
>>> message[-1]
'a'
>>> message[-index]
'e'
>>> message[15]
message[15]
IndexError: string index out of range
Py th on str in g s a r e im m u ta ble
message[6] = 'S'
'Computer Science'
>>> 'Hi' * 3
'HiHiHi'
'C'
'AZ'
' sir'
6.1.1 Slicing
>>> message[0:5]
'Hello'
>>> message[-10:-5]
'Hello'
>>> message[:5]
'Hello'
>>> message[5:]
' Sita'
>>> message[:]
'Hello Sita'
'Hello Sita'
>>> message[:15]
'Hello Sita'
>>> message[15:]
''
'Hello Sita'
>>> message[8:20]
'ta'
>>> message[6:None]
'Sita'
Apart from extracting a consecutive subsequence of
characters from a string, Python also allows us to extract
a subsequence of the form start:end:inc. This
subsequence will include every incth element of the
sequence in the range start to end-1, for example:
>>> message[0:len(message):2]
'HloSt'
>>> message[0:len(message):3]
'HlSa'
6.1.2 Membership
True
True
False
>>> helloSpaced
'h e l l o'
Function count
>>> 'Encyclopedia'.count('c')
>>> vowelCount = 0
>>> vowelCount
vowels = 'AEIOUaeiou'
>>> colors.find('red')
23
>>> colors.find('orange')
-1
'Python is a language'
False
True
True
>>> 'python'.islower()
True
>>> 'Python'.isupper()
False
True
False
>>> '123'.istitle()
False
True
Function replace
>>> colors.split(',')
>>> colors.split()
Function join
'I am ok'
"' > I > ' > , > > ' > a > m > ' > , > > '
> o > k > '"
In the first example, the sequence comprises three
elements, namely, 'I', 'am', and 'ok', which are
combined to form the string 'I > am > ok'. In the
second example, we use space as a delimiter instead of
>. In the third example, each character in the string
"'I > am > ok'" is an element of the sequence of
characters in "'I > am > ok'".
Does a str in g com pr ises a lph a bets, dig its, or w h itespa ces
on ly ?
>>> name.isalpha()
True
>>> name.isalpha()
False
== 10
True
True
>>> password.isalnum()
True
>>> password.isalnum()
False
Function startswith and endswith
>>> name.endswith('Talwar')
True
True
False
b'\xff\xfe\x00\x00m\x00\x00\x00e\x00\x00\x
00s\x00\x00\x00s\x00\x00\x00a\x00\x00\x00g
\x00\x00\x00e\x00\x00\x00'
>>> str1.decode('utf32')
'message'
List of Functions
16
den oted by
a sequ en ce of a lph a n u m er ic ch a r a cter s
[a-z0-9]+
den oted by
a r epea tin g (0 or m or e tim es) sequ en ce of
(\.[a-z0-
dots follow ed by a lph a n u m er ic ch a r a cter s
9]+)*
@ den oted by @
den oted by
sequ en ce of a lph a betic ch a r a cter s
[a-z]+
>>> match.group()
'ram@gmail'
print(i.group())
ram@gmail.com
pranav.gupta@cs.iitd.ac.in
nik@yahoo.com
raman@gmail.com
print(i.group())
Walking
thinking
coming
>>> len(words)
13
>>> re.findall(r'([a-z0-9]+(\.[a-z0-
9]+)*@[a-z]+(\.[a-z]+)+)', 'ram@gmail.com,
pranav.gupta@cs.iitd.ac.in, nik@yahoo.com,
raman@gmail.com')
ex tr a ctin g com m en ts
"""
"""
a = 5 #number1
b = 5 #number2
c = a + b
'''
print(i.group())
#number1
#number2
print(i.group())
"""
"""
Aiysha,Renuka,Robin
Sneha,Ravi''')
SUMMARY
S.cou
Cou nt s nu mb er of t i mes st r i ng str oc c u r s i n t h e st r i ng
nt(st
S.
r)
S.rfi
Ret u r ns i ndex of t h e l ast oc c u r r enc e of st r i ng str i n
nd(st
st r i ng S, and r et u r ns -1 i f str i s not p r esent i n st r i ng S.
r)
S.cap
Ret u r ns a st r i ng t h at h as f i r st l et t er of t h e st r i ng S i n
itali
u p p er c ase and r est of t h e l et t er s i n l ow er c ase.
ze()
Ret u r ns a st r i ng t h at h as f i r st l et t er of ev er y w or d i n
S.tit
t h e st r i ng S i n u p p er c ase and r est of t h e l et t er s i n
le()
l ow er c ase.
Ret u r ns a st r i ng t h at h as al l u p p er c ase l et t er s i n
S.low
st r i ng S c onv er t ed i nt o c or r esp ondi ng l ow er c ase
er()
l et t er s.
Ret u r ns a st r i ng t h at h as al l l ow er c ase l et t er s i n
S.upp
st r i ng S c onv er t ed i nt o c or r esp ondi ng u p p er c ase
er()
l et t er s.
S.isl
Ret u r ns True i f al l al p h ab et s i n st r i ng S ar e i n
ower(
l ow er c ase, el se False.
)
S.isu
Ret u r ns True i f al l al p h ab et s i n st r i ng S ar e i n
pper(
u p p er c ase, el se False.
)
S.rep
lace( Ret u r ns a st r i ng t h at h as ev er y oc c u r r enc e of st r i ng
str1, str1 i n S r ep l ac ed w i t h an oc c u r r enc e of st r i ng str2.
str2)
S.par
Par t i t i ons t h e st r i ng S i nt o t h r ee p ar t s b ased on
titio
delimiter and r et u r ns a t u p l e c omp r i si ng t h e st r i ng
n(del
b ef or e delimiter, delimiter i t sel f and t h e st r i ng af t er
imite
delimiter.
r)
S.joi
n(seq Ret u r ns a st r i ng c omp r i si ng el ement s of t h e sequence
uence sep ar at ed b y del i mi t er S.
)
S.isa
Ret u r ns True i f al l c h ar ac t er s i n st r i ng S c omp r i se
lpha(
al p h ab et s onl y , and False ot h er w i se.
)
S.isd
Ret u r ns True i f al l c h ar ac t er s i n st r i ng S c omp r i se
igit(
di gi t s onl y , and False ot h er w i se.
)
S.isa
Ret u r ns True i f al l c h ar ac t er s i n st r i ng S c omp r i se
lnum(
al p h ab et s and di gi t s onl y , and False ot h er w i se.
)
S.sta
rtswi Ret u r ns True i f st r i ng S st ar t s w i t h st r i ng str, and
th(st False ot h er w i se.
r)
S.end
Ret u r ns True i f st r i ng S ends w i t h st r i ng str, and False
swith
ot h er w i se.
(str)
S.enc
ode(e Ret u r ns S i n an enc oded f or mat , b ased on t h e gi v en
ncodi encoding sc h eme.
ng)
S.dec
ode(e Ret u r ns t h e dec oded st r i ng S, b ased on t h e gi v en
ncodi encoding sc h eme.
ng)
EXERCISES
CHAPTER OUTLINE
7 .1 Lists
7 .2 Sets
7 .3 Tu ples
7 .4 Diction a r y
7.1 LISTS
>>> id(subjects)
57135752
>>> id(temporary)
57135752
lists a r e m u ta ble
>>> print(temporary)
>>> print(subjects)
57135752 57135752
>>> subjectCodes[1]
['English', 85]
>>> print(subjectCodes[1]
[0],subjectCodes[1][1])
English 85
>>> details
print(name)
Ram
Shyam
Gita
Sita
>>> count = 0
count += 1
>>> count
>>> list(vowels)
>>> a.append(35)
>>> a
>>> a.extend([35,40])
>>> a
>>> a.extend('abc')
>>> a
>>> a.count(20)
pop: The function pop returns the element from the list
whose index is passed as an argument, while removing it
from the list, for example:
>>> a.pop(3)
10
>>> a.pop(3)
50
>>> a
>>> a.remove(20)
>>> a
>>> rollNums.pop(names.index('Shyam'))
>>> names.remove('Shyam')
deletin g a n object
>>> a
>>> del a
>>> a
>>> names
>>> names.reverse()
>>> names
>>> names.sort()
>>> names
>>> names
>>> names
>>> end = 10
cubes.append(i ** 3)
>>> cubes
>>> tall
>>> s2 = [3, 5]
>>> crossProduct
>>> list1[1] = 22
>>> list1
>>> list2
>>> list1[1] = 25
>>> list1
>>> list3
>>> list1[2][0] = 35
>>> list1
>>> list3
>>> list1[2][0] = 35
>>> list1
>>> list4
>>> cube(3)
27
>>> sum2Cubes(2, 3)
35
[1, 2, 3, 4, 5]
>>> sumCubes
225
[8, 64]
>>> sumEvenCubes
72
>>> sumEvenCubes
72
7.2 SETS
{1, 2, 3}
>>> vowels
>>> vehicles
>>> digits
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
e a o u i
The functions min, max, sum, and len work for sets in
the same manner as defined for lists.
>>> min(digits)
>>> max(digits)
>>> sum(digits)
45
>>> len(vehicles)
True
>>> vehicles.add('Bus')
>>> vehicles
>>> vehicles
r em ov in g a n elem en t fr om th e set
>>> heavyVehicles.remove('Crane')
>>> heavyVehicles
{'Bus', 'Truck'}
>>> heavyVehicles.remove('Car')
Traceback (most recent call last):
heavyVehicles.remove('Car')
KeyError: 'Car'
>>> heavyVehicles.pop()
'Bus'
r em ov in g a ll elem en ts of a set
>>> heavyVehicles.clear()
>>> heavyVehicles
set()
u n ion of tw o sets
>>> eatables
>>> eatables
>>> fruitsAndVegetables =
fruits.intersection(vegetables)
>>> fruitsAndVegetables
>>> fruitsAndVegetables
set differ en ce
>>> onlyFruits =
fruits.difference(vegetables)
>>> onlyFruits
{'Orange', 'Apple'}
>>> onlyFruits
{'Orange', 'Apple'}
>>> onlyVegetables =
vegetables.difference(fruits)
>>> onlyVegetables
{'Cauliflower', 'Potato'}
{'Cauliflower', 'Potato'}
>>> fruitsXORVegs
sy m m etr ic differ en ce
>>> fruitsXORVegs =
fruits.symmetric_difference(vegetables)
>>> fruitsXORVegs
{2}
{1, 3}
>>> digits
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> digits2
{0, 1, 2, 3, 7, 8, 9}
>>> isSubset
True
>>> isSuperset
True
>>> type(t1)
<class 'tuple'>
>>> (2)
>>> (2,)
(2,)
>>> 2, 4, 6
(2, 4, 6)
>>> t1[1] = 3
t1[1] = 3
>>> t1[2][1] = 5
>>> t1
>>> tuple(vowels)
>>> tuple(range(5))
(0, 1, 2, 3, 4)
>>> fruitColor
>>> fruitColorQuantity =
list(zip(fruitColor, quantity))
>>> fruitColorQuantity
>>> age.count(18)
>>> age.index(18)
>>> month = {}
>>> month
>>> type(month)
<class 'dict'>
20
>>> price['carrot']
20
>>> price.keys()
>>> price.values()
>>> price.items()
key s a r e im m u ta ble
>>> price['tomato'] = 25
>>> 2 in winter.keys(),
min(winter.keys()), max(winter.keys()),
sum(winter.keys())
7.4.2 Deletion
r em ov in g a key -v a lu e pa ir
>>> winter
clear(): to r em ov e a ll key -v a lu e pa ir s
>>> winter = {11:'November ', 12:
'December', 1:'January', 2:'February'}
>>> months.clear()
({}, {})
>>> passwords.get('Ram',-1)
'ak@607'
-1
>>> print(passwords.get('Raman'))
None
>>> passwords.update(morePasswords)
>>> passwords
(54782832, 54781104)
>>>
Inverted Dictionary:
SUMMARY
>>> list2 * 2
Mu l t i p l i c at i on op er at or *
[10, 20, 30, 10, 20, 30]
>>> len(list1)
Lengt h op er at or l en
3
>>> list2[-1]
Index i ng
30
>>> list2[0:2]
Sl i c i ng [10, 20]
Sy nt ax : start:end:inc >>> list2[0:3:2]
[10, 30]
>>> min(list2)
Fu nc t i on min
10
>>> max(list1)
Fu nc t i on max
'Red'
>>> 40 in list2
Memb er sh i p op er at or in
False
L.append
Inser t s t h e el ement e at t h e end of t h e l i st L.
(e)
L.insert
Inser t s el ement e at i ndex i i n t h e l i st L.
(i,e)
L.revers
Rev er ses t h e or der of el ement s i n t h e l i st L.
e()
F unction De scription
>>> t1 * 2
Mu l t i p l i c at i on
('Monday', 'Tuesday', 'Monday',
op er at or *
'Tuesday')
>>> t3 = t1 + ('Wednesday',)
Conc at enat i on
>>> t3
op er at or +
('Monday', 'Tuesday', 'Wednesday')
>>> len(t1)
Lengt h op er at or len
2
>>> t2[-2]
Index i ng
20
Sl i c i ng
>>> t1[1:2]
Sy nt ax :
'Tuesday'
start:end:inc
>>> min(t2)
Fu nc t i on min
10
>>> max(t2)
Fu nc t i on max
30
Fu nc t i on sum
>>> sum(t2)
(not def i ned on
60
st r i ngs)
F unction Explanation
T.index(e
Ret u r ns i ndex of t h e el ement e f r om t u p l e L.
)
F uncti
De scription
on
D.valu
es() Ret u r n an ob jec t c omp r i si ng of al l v al u es of
di c t i onar y D.
D.clea Remov es al l k ey –v al u e p ai r s f r om di c t i onar y D.
r()
D.copy
Cr eat es a sh al l ow c op y of di c t i onar y D.
()
D1.upd
A dds t h e k ey –v al u e p ai r s of di c t i onar y D2 i n
ate(D2
di c t i onar y D1.
)
EXERCISES
CHAPTER OUTLINE
8 .1 Recu r siv e Solu tion s for Pr oblem s on Nu m er ic Da ta
8 .4 Pr oblem of Tow er of Ha n oi
8.1.1 Factorial
Iterative Approach
Recursive Approach
or equivalently as
factorial(n) = 1 if n==0 or 1
= n * factorial(n-1) if n > 1
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * 1))
= 3 * 2
= 6
def factorial(n):
'''
'''
assert n >= 0
if n == 0 or n == 1:
return 1
return n * factorial(n-1)
a lter n a tiv e defin ition for fu n ction fa ctor ia l
0, 1, 1, 2, 3, 5, 8, 13, 21, …
Iterative Approach
Recursive Approach
= (1 + fibo(1)) + fibo(2)
= (1 + 0) + fibo(2)
= 1 + fibo(2)
= 1 + 1
= 2
pr efer iter a tiv e solu tion ov er r ecu r siv e if iter a tiv e solu tion is
sim pler to con ceiv e
length('Zero') = 1 + length('ero')
= 1 + (1 + length('ro'))
= 1 + (1 + (1 + length('o')))
= 1 + (1 + (1 + (1 + length(''))))
= 1 + (1 + (1 + (1 + 0)))
= 1 + (1 + (1 + 1))
= 1 + (1 + 2)
= 1 + 3
= 4
Fig. 8.7 Pr og r a m to deter m in e len g th of th e str in g (lenStr.py)
Figure 8.8 gives stack frames created and exited on the
execution of the script lenStr with 'Zero' as an input
value for str1, as visualized in Python Tutor.
= 'o' + 'reZ'
= 'oreZ'
Fig. 8.8 Recu r siv e ca lls to fu n ction length
Fig. 8.9 Pr og r a m to r ev er se th e str in g (reverse.py)
8.2.3 Palindrome
isPalindrome('noon') = str1[0]==str1[-1]
and isPalindrome('oo')
= True
if i is not a list
otherwise,
flatten list i
h a r d-codin g th e v a lu es of v a r ia bles
Fig. 8.13 Pr og r a m to fla tten a list (flatten.py)
8.3.2 Copy
copy in g a list
Fig. 8.15 Pr og r a m to cr ea te copy of a list (copy.py)
8.3.4 Permutation
insert 3 at pos
print perm
n = 1
Tow er of Ha n oi h a v in g on e disk
n = 3
Tow er of Ha n oi h a v in g tw o disks
Tow er of Ha n oi h a v in g th r ee disks
SUMMARY
EXERCISES
CHAPER OUTLINE
9 .1 File Ha n dlin g
9 .3 Er r or s a n d Ex ception s
>>> f = open('PYTHON','w')
read(): to r ea d a file
>>> f.write('''Python:
130
Note that apart from writing the given data into a file,
the function write also returns the number of
characters written into the file (130 in the above
example). Since the file is opened in write mode, Python
disallows read operation on it by flagging an error as
shown below:
>>> f.read()
f.read()
>>> f.close()
>>> f.read()
'Python:\nPython is an interactive
programming language.\nSimple syntax of
the language makes Python programs easy to
read and write.'
>>> f.close()
>>> print(f.read())
Python:
>>> f.close()
>>> f = open('PYTHON','r')
>>> f.tell()
>>> f.read(4)
'Pyth'
>>> f.tell()
'on:\n'
>>> f.tell()
Note that so far we have read only eight bytes from the
input file. However, the function f.tell() shows 9 as
the current position in the file. This is because the end of
line character '\n' is stored by WINDOWS operating
system as a pair of characters, namely, carriage return
character (CR) to transfer control to beginning of line
and line feed character (LF) to transfer control to the 1
next line. However, if we are using a linux/UNIX®
based systems, the function tell would return the
position 8 as shown below:
>>> f.tell()
>>> f.read(4)
'on:\n'
>>> f.tell()
>>> f.readline()
>>> f.readline()
>>> f.readline()
''
Note that, when all the contents of a file have been read,
a further read operation on it will return a null string.
One way to read from a particular position in a file is to
use the function seek(). For example, for reading from
the beginning of the file, we may invoke the seek
function with the argument 0 as shown below:
>>> f.seek(0)
>>> f.writelines(description)
>>> f.close()
>>> f.read()
'Python:\nPython is an interactive
programming language.\n'
>>> f.close()
>>> f2.write(data)
55
>>> f1.close()
>>> f2.close()
31
44
>>> f.close()
>>> f.read()
'Python:\nPython is an interactive
programming language.\nSimple syntax of
the language makes Python programs easy to
read and write'
>>> f.close()
sy n ta x er r or : v iola tion of Py th on g r a m m a r r u le
>>> print('Hello)
In den ta tion er r or
1 . NameError
Th is ex ception occu r s w h en ev er a n a m e th a t a ppea r s
in a sta tem en t is n ot fou n d g loba lly . For ex a m ple, in
th e follow in g sta tem en t, w e in ten d to ta ke m a r ks a s a n
in pu t fr om th e u ser . For doin g so, w e in ten ded to u se
fu n ction input bu t in stea d ty ped Input. Py th on bein g
ca se-sen sitiv e fa ils to r ecog n ize th e fu n ction input a n d
th e sy stem r espon ds w ith th e er r or m essa g e
NameError: name 'Input' is not defined. Th is
m essa g e beg in s w ith th e n a m e of th e ex ception . Note
th a t th e follow in g Traceback object descr ibes th a t
er r or occu r r ed in lin e 1 in Py th on sh ell, in th e m ost
r ecen t ca ll:
name not f ou nd gl ob al l y
>>> print(price)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(price)
NameError: name 'price' is not defined
2 . TypeError
Th is ex ception occu r s w h en a n oper a tion or fu n ction is
a pplied to a n object of in a ppr opr ia te ty pe. For ex a m ple,
th e ex pr ession 'sum of 2 and 3 is ' + 5 in v olv es
a ddin g a n u m ber to a str in g w h ich is n ot a v a lid
oper a tion r esu ltin g in a n ex ception .
Inv al i d t y p e of op er ands f or t h e op er at i on
3 . ValueError
Th is ex ception occu r s w h en ev er a n in a ppr opr ia te
a r g u m en t v a lu e, ev en th ou g h of cor r ect ty pe, is u sed
in a fu n ction ca ll, for ex a m ple:
Inv al i d ar gu ment v al u e
>>> int('Hello')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
int('Hello')
ValueError: invalid literal for int() with
base 10: 'Hello'
at t emp t t o di v i de b y zer o
>>> 78/(2+3-5)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
78/(2+3-5)
ZeroDivisionError: division by zero
5 . OSError
Th is ex ception occu r s w h en ev er th er e is a sy stem
r ela ted er r or su ch a s disk fu ll or a n er r or r ela ted to
in pu t/ou tpu t, for ex a m ple, open in g a n on -ex isten t file
for r ea din g or r ea din g a file open ed in w r ite m ode:
sy st em r el at ed er r or
>>> f = open('passwordFile.txt')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
f = open('passwordFile.txt')
FileNotFoundError: [Errno 2] No such file or
directory: 'passwordFile.txt'
6 . IndexError
Th is ex ception occu r s w h en ev er w e tr y to a ccess a n
in dex th a t is ou t of a v a lid r a n g e. For ex a m ple, let u s
n a m e th e list of color s ['red', 'green', 'blue'], a s
colors. Now th e v a lid r a n g e of in dex es for colors is
[-3, -2, -1, 0, 1, 2] a n d th e v a lid in dex r a n g e of
in dex es for th e str in g colors[2] is [-4, -3, -2, -1,
0, 1, 2, 3]. A ccessin g a n in dex ou tside a v a lid r a n g e
w ill ca u se IndexError exception to occu r :
ac c essi ng an i nv al i d i ndex
(<class 'FileNotFoundError'>,
FileNotFoundError(2, 'No such file or
directory'), <traceback object at
0x02EB2530>)
> >>
(<class 'ZeroDivisionError'>,
ZeroDivisionError('float division by
zero',), <traceback object at 0x039BD2B0>)
except:
(<class 'AssertionError'>,
AssertionError(), <traceback object at
0x0356D328>)
(<class 'AssertionError'>,
AssertionError(), <traceback object at
0x03B42508>)
>>>
Bye
main()
> >>
Bye
4001,Nitin Negi,75
4002,Kishalaya Sen,98
4003,Kunal Dua,80
4004,Prashant Sharma,60
4005,Saurav Sharma,88
4001,Nitin Negi,78.0
4002,Kishalaya Sen,100
4003,Kunal Dua,83.0
4004,Prashant Sharma,63.0
4005,Saurav Sharma,91.0
Fig. 9.11 Pr og r a m to com pu te m oder a ted m a r ks
(moderatedMarks.py)
1001,Vinay Kumar,30
1002,Rohit Sen,35
1003,Vinita Sharma,28
1004,Bijoy Dutta,35
1001,245
1002,0
1003,0
1004,240
To compute the monthly wages of all employees, we
need to read the files employeeMaster and
empMonthly and produce a third file monthlyWages
containing monthly wages of the employees. We
describe this task in the form of a pseudocode (Fig. 9.12).
Fig. 9.12 Pseu docode to com pu te con ten ts for file monthlyWages
1001,7350
1002,0
1003,0
1004,8400
Fig. 9.13 Pseu docode to com pu te con ten ts for file monthlyWages
Fig. 9.14 Pr og r a m to g en er a te sa la r y (salaryGen.py)
In the above program, we assume that the information
about each employee in empMaster is available in
empMonthly. Suppose, the file empMonthly does not
contain an entry for employees for whom hrlyWorked
is equal to 0. Sample data in this file is shown below:
1001,245
1004,240
1001,7350
1002,0
1003,0
1004,8400
Fig. 9.16 Pr og r a m to g en er a te sa la r y (salaryGen.py)
SUMMARY
EXERCISES
CHAPER OUTLINE
1 0.1 Cla sses a n d Objects
1 0.4 Da te Cla ss
>>> name.lower()
'raman'
'raman'
class ClassName:
classBody
>>> p1 = Person('Amir','24-10-1990',
'38/4, IIT Delhi 110016')
The execution of the above statement does three things:
>>> p2 = Person('Riya','11-10-1992','C-
3,Vivek Vihar, Delhi-92')
object a ttr ibu tes: da ta m em ber s a n d m eth ods a ssocia ted w ith
a n in sta n ce of a cla ss
Fig. 10.2 Py th on Tu tor v isu a liza tion of objects p1 a n d p2, a n d
cla ss a ttr ibu tes
p1 = Person('Amir','24-10-1990','38/4, IIT
Delhi 110016')
p2 = Person('Riya','11-10-1992','C-3,Vivek
Vihar, Delhi-92')
oper a tion s su ppor ted by a cla ss: in sta n tia tion a n d a ttr ibu te
r efer en ces
True
True
True
>>> int.__str__(7)
'7'
>>> print(int.__str__(7))
print(7)
print(str(7))
p1.__str__()
'Name:Amir\nDOB:24-10-1990\nAddress:38/4,
IIT Delhi 110016'
and
print(p1.__str__())
Name:Amir
DOB:24-10-1990
>>> print(p1)
>>> p1.setDOB('24-10-1991')
>>> print(p1)
Name:Amir
DOB:24-10-1991
10.2.1 Destructor
>>> p1 = Person('Amir','24-10-1990','38/4,
IIT Delhi 110016')
>>> p2 = Person('Riya','11-10-1992','C-
3,Vivek Vihar, Delhi-92')
>>> p3 = p2
>>> print(Person.count)
>>> del p1
Deleted !!
>>> print(p1)
print(p1)
>>> print(Person.count)
>>> del p2
>>> print(Person.count)
>>> del p3
Deleted !!
>>> print(Person.count)
a bstr a ct da ta ty pe
>>> print(p1.__str__())
Name:Amir
DOB:24-10-1991
>>> print(Person.__str__(p1))
Name:Amir
DOB:24-10-1991
defa u lt da te
01-01-2000
v a lida tin g da te
SUMMARY
EXERCISES
Marks Grade
>= 90 A
<40 E
Percentage Division
>= 60 I
>= 5,00,000 8
< 1 ,00,000 3
CHAPER OUTLINE
1 1 .1 Poly m or ph ism
1 1 .6 Com position
1 1 .7 In h er ita n ce
11.1 POLYMORPHISM
(5,7)
Comparing Dates
>>> id(date1)
49078096
10775792
False
True
False
>>> dates.sort()
print(date)
31-10-2014
17-12-2014
31-12-2014
Fig. 11.5 Da te cla ss m eth ods __lt__
def area(radius):
return areaCirc
return areaRect
>>> area(4)
Traceback (most recent call last):
area(4)
>>> area(4, 5)
20
'''
Inputs:
'''
if b == None:
areaCirc = 3.14 * a * a
return areaCirc
else:
return areaRect
today = MyDate(31,1,2014)
today.day = 15
>>> print(today.__day)
print(today.__day)
<instance>._<className><attributeName>
today.weekDay = 'Wednesday'
Once all the methods of the class have been defined, one
may realize the need to add another method to the class
or a particular instance of the class. Python allows us to
add methods dynamically to a class using the syntax:
<className>.<newMethodName> =
<existingFunctionName>
>>> print(s1.percentage())
90.0
<instance>.
<newMethodName>=MethodType(<existingFuncti
onName>,<instance>)
>>> s1.result()
'pass'
>>> s2.percentage()
98.0
>>> s2.result()
s2.result()
AttributeError: 'Student' object has no
attribute 'result'
11.6 COMPOSITION
>>> print(p1)
Name:Rajat Mittal
DOB:24-10-1990
Address:B-23,Malviya Nagar,Delhi
11.7 INHERITANCE
>>> dir(object)
['__class__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__',
'__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__',
'__subclasshook__']
'B-23,Malviya Nagar,Delhi')
>>> print(Person.personCount)
>>> print(Employee.employeeCount)
>>> print(Person.personCount)
Deleted!!
>>> print(Employee.employeeCount)
0
>>> print(Person.personCount)
or
super(Employee, self).__del__()
or
super().__del__()
Scope Rule
ob1:
ob2:
w:100, x:6, y:10, z:30, v:50
dir(A):
dir(ob1):
dir(B):
dir(ob2):
['__class__', '__delattr__', '__dict__',
'__dir__', '__doc__', '__eq__',
'__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__',
'__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__',
'__weakref__', 'v', 'w', 'x', 'y', 'z']
>>> str.__bases__
(<class 'object'>,)
>>> B.__bases__
(<class '__main__.A'>,)
>>> B.__bases__[0]
<class '__main__.A'>
>>> 'Python'.__class__.__name__
'str'
>>> n1 = MyInt(3456)
>>> n2 = MyInt(-18)
>>> len(n1)
>>> len(n2)
>>> len(MyInt(0))
>>> n1 + n2
3438
>>> n1 - n2
3474
m u ltilev el in h er ita n ce
Fig. 11.16 In h er ita n ce r ela tion sh ip betw een Em ploy ee, Cler k, a n d
Ma n a g er
>>> print(clerk1)
Name:Arun
DOB:05-06-1930
Id:1001
Salary:20000
Date of Joining:05-06-1950
Fig. 11.17 Cla sses Clerk a n d Manager
>>> print(manager1)
Name:Rehman
DOB:05-06-1970
Id:1002
Salary:52000
Date of Joining:05-06-1990
ManagerialPay:2000
>>> print(manager1.getSalary())
52000
>>> print(currentTime)
23:50:30
>>> print(meetStaff)
15-7-2014, 10:00:00
a bstr a ct m eth ods a n d a bstr a ct cla sses iden tify fu n ction a lity
th a t sh ou ld be im plem en ted by a ll th e su bcla sses
__metaclass__ = ABCMeta
To illustrate the use of abstract classes, we create an
object rectangle of the class Rectangle having
length and breadth 30 and 15, respectively, and an
object circle of the class Circle having radius 5.
The methods area and perimeter defined in the
subclasses Rectangle and Circle override the
corresponding abstract methods defined in the superclass
Shape. Next, we see some examples of the use of these
methods:
>>> rectangle.area()
450
>>> rectangle.perimeter()
90
>>> circle.area()
78.5
>>> circle.perimeter()
31.4
>>> C.__mro__
>>> B2.__mro__
>>> B1.__mro__
>>> A.__mro__
issubclass()
issubclass(sub, super)
True
To find whether the instance obj is an object of class
class1, we use the function isinstance:
isinstance()
isinstance(obj, class1)
True
True
False
>>>
hasattr()
False
>>> hasattr(manager1, 'DOB')
True
getattr() a n d setattr()
getattr(obj, attr)
15
>>> print(meetStaff)
23-07-2014, 10:00:00
delattr()
delattr(obj, attr)
>>> print(meetStaff)
File "F:\PythonCode\Ch11\appointment.py",
line 28, in __str__
+'\n'+self.description
if self.day <= 9:
SUMMARY
EXERCISES
CHAPTER OUTLINE
1 2 .1 Sor tin g
1 2 .2 Sea r ch in g
1 2 .3 A Ca se Stu dy
12.1 SORTING
Suppose we need to arrange a list of names in
lexicographic order, i.e., as they appear in a dictionary.
Examine the sample data that appears in the list names
(Fig. 12.1).
Sorted List
Sorted List
324
Fig. 12.17 Pr og r a m for bu bble sor t (bubbleSort.py)
Sorted List
Sorted List
325
temp = 'Maya'
i = 4
temp = lst[i]
j = i - 1
while j >= 0 and lst[j] > temp:
lst[j + 1] = lst[j]
j = j-1
lst[j + 1] = temp
Sorted List
12.2 SEARCHING
332
Fig. 12.33 Fu n ction for bin a r y sea r ch
!
12.3 A CASE STUDY
337
Fig. 12.38 Cla ss Section (section.py)
1 . __init__()
Th e __init__ m eth od (Fig . 1 2 .4 1 ) in itia lizes a n
in sta n ce of th e Section cla ss by in itia lizin g its list
records (of th e Student cla ss) a s a n em pty list.
2 . readList(self, source)
Th e readList m eth od (Fig . 1 2 .4 2 ) a ccepts th e n a m e of
th e source file con ta in in g Student objects a s a n in pu t
pa r a m eter a n d a ppen ds th e Student objects r ea d fr om
th e source file to th e list records of th e Section
in sta n ce a t h a n d.
3 . writeList(self, destination)
Th e writeList m eth od (Fig . 1 2 .4 3 ) a ccepts th e n a m e
of th e destination file a s a n in pu t pa r a m eter a n d
w r ites to it on e by on e th e Student objects in th e list
records of th e Section in sta n ce a t h a n d.
5 . isSorted(self)
If th e list records is a r r a n g ed in a scen din g or der of th e
v a lu es of th e key rollNo, th e m eth od isSorted (Fig .
1 2 .4 5 ) r etu r n s True, oth er w ise it r etu r n s False.
6 . binarySearch(self, rollNo)
Th e binarySearch m eth od (Fig . 1 2 .4 6 ) is a pplica ble if
th e list records is a lr ea dy sor ted. It a ccepts rollNo a s
a n in pu t pa r a m eter . Th e Student objects a r e sea r ch ed
for th e g iv en rollNo in th e list records u sin g th e
bin a r y sea r ch pr ocedu r e descr ibed in th e pr ev iou s
section . If a Student object w ith th e g iv en rollNo is
fou n d in th e list records, th e m eth od r etu r n s th e in dex
of th e m a tch ed object, oth er w ise it r etu r n s None.
7 . linearSearch(self, rollNo)
Th e linearSearch m eth od (Fig . 1 2 .4 7 ) is u sed if th e
list records is n ot sor ted. It a ccepts rollNo a s a n in pu t
pa r a m eter . Th e Student objects a r e sea r ch ed
sequ en tia lly in th e list records for th e g iv en rollNo in
th e list records u sin g th e lin ea r sea r ch pr ocedu r e
descr ibed in th e pr ev iou s section . If a Student object
w ith th e g iv en rollNo is fou n d in th e list records, th e
m eth od r etu r n s th e in dex of th e m a tch ed object,
oth er w ise it r etu r n s None.
8 . insertionSort(self)
In th e pr ev iou s section , w e discu ssed th r ee tech n iqu es
of sor tin g a list of objects. Now , w e m a ke u se of th e
in ser tion sor t tech n iqu e (Fig . 1 2 .4 8 ) to sor t th e list
records of Student objects, ba sed on rollNo.
9 . delete(self, rollNo)
Th e delete m eth od (Fig . 1 2 .4 9 ) a ccepts rollNo a s th e
in pu t pa r a m eter . It sea r ch es th e en tir e list records
sequ en tia lly for th e Student object h a v in g th e g iv en
rollNo. If th e desir ed Student object is fou n d, it is
r em ov ed fr om th e list records a n d th e m eth od r etu r n s
th e m essa g e 'Record deleted successfully' to
in dica te su ccessfu l ter m in a tion . How ev er , if th e
desir ed Student object h a v in g th e g iv en rollNo is n ot
fou n d, th e m eth od r etu r n s th e m essa g e 'Record not
found'.
del et i ng a Student i nst anc e w i t h t h e gi v en r ol l nu mb er f r om t h e
l i st records
1 1 . __str__(self)
Th e m eth od __str__ (Fig . 1 2 .5 1 ) of cla ss Section
con str u cts th e str in g r epr esen ta tion for a n in sta n ce of
th e cla ss. It tr a v er ses th e list records in v okin g
__str__ fu n ction for ea ch Student object.
3 found at index 4
6 not found
SUMMARY
1 . Th e pr ocess of a r r a n g in g da ta in a scen din g /descen din g
or der is ca lled sor tin g . Th e a ttr ibu te th a t for m s th e
ba sis of sor tin g is ca lled key .
2 . In selection sor t, to beg in w ith , w e fin d th e sm a llest
v a lu e in th e list, a n d in ter ch a n g e th is en tr y w ith th e
fir st en tr y in th e list. Nex t, w e fin d th e en tr y w ith th e
sm a llest v a lu e ou t of th e r em a in in g en tr ies, a n d
in ter ch a n g e it w ith th e secon d v a lu e in th e list, a n d
pr oceed in th is m a n n er . If th er e a r e n v a lu es, on ly (n −
1 ) v a lu es n eed to be pla ced in or der beca u se w h en (n −
1 ) v a lu es h a v e been pu t in th e pr oper pla ce, th en th e
nth v a lu e w ou ld a u tom a tica lly be in or der .
3 . In bu bble sor t, in ea ch pa ss, w e com pa r e v a lu es in
a dja cen t position s a n d in ter ch a n g e th em , if th ey a r e
ou t of or der . Su ppose w e h a v e a list of n v a lu es. To
beg in w ith , th e nth a n d (n − 1 )th v a lu es a r e com pa r ed
a n d in ter ch a n g ed if fou n d ou t of or der ; th en (n − 1 )th
a n d (n − 2 )th v a lu es a r e com pa r ed a n d in ter ch a n g ed if
fou n d ou t of or der , a n d so on . Obser v e th a t in th e fir st
pa ss th e sm a llest v a lu e w ill m ov e to th e fr on t of th e list
a t in dex 0; on su bsequ en t pa sses, it w ill be ig n or ed.
A fter n − 1 iter a tion s, th e list w ill be com pletely sor ted
a n d th e a lg or ith m w ill h a lt.
4 . In in ser tion sor t, th e list is log ica lly div ided in to tw o
pa r ts. Wh er ea s th e left pa r t is th e sor ted pa r t, th e r ig h t
pa r t is u n sor ted pa r t com pr isin g th e elem en ts y et to be
a r r a n g ed in sor ted or der . In ea ch iter a tion , w e in cr ea se
th e len g th of th e sor ted pa r t by on e in th e follow in g
m a n n er : in ser t th e fir st elem en t fr om th e u n sor ted
pa r t in th e sor ted pa r t a t th e cor r ecft position . To fin d
th e cor r ect position of th e v a lu e to be in ser ted, w e
com pa r e it w ith v a lu es in sor ted pa r t a n d sh ift ea ch
v a lu e to th e r ig h t by on e position , u n til th e cor r ect
position is fou n d.
5 . Sea r ch in g is th e ta sk of fin din g w h eth er a da ta v a lu e
a ppea r s in a list.
6 . In lin ea r sea r ch of a da ta v a lu e in a list, w e sca n th e list
fr om th e beg in n in g till th e da ta v a lu e is fou n d, or th e
list is ex h a u sted. Th is tech n iqu e is kn ow n a s lin ea r
sea r ch a s th e or der of sea r ch is lin ea r or sequ en tia l in
n a tu r e.
7 . Bin a r y sea r ch is u sed in ca se th e list to be sea r ch ed is
a lr ea dy sor ted. For sea r ch in g a da ta v a lu e in th is list,
w e pr oceed a s follow s: fir st, w e ex a m in e th e m iddle
elem en t of th e list, if it is equ a l to th e da ta v a lu e th a t
w e a r e lookin g for , w e w ill stop. If w e do n ot fin d th e
elem en t a t th e m iddle position , w e w ill on ly h a v e to
sea r ch on th e left or th e r ig h t of th e m iddle elem en t
depen din g on w h eth er th e da ta v a lu e a t th e m iddle
position is g r ea ter or sm a ller th a n th e da ta v a lu e w e
a r e lookin g for .
8 . Mer g e sor t a n d qu ick sor t m eth ods m a ke sig n ifica n tly
less n u m ber of com pa r ison s a s com pa r ed to selection
sor t, in ser tion sor t, a n d bu bble sor t m eth ods.
EXERCISES
1. 15
2. 25
3. 55
4. 40
5. 22
5 . Wr ite a fu n ction leftCirculate th a t ta kes a list a s a n
in pu t a n d left cir cu la tes th e v a lu es in th e list so th a t in
th e fin a l list, ea ch v a lu e is left sh ifted by on e position
a n d leftm ost v a lu e in th e or ig in a l list n ow a ppea r s a s
th e r ig h tm ost v a lu e. For ex a m ple, on ex ecu tion of th e
fu n ction on th e list [1, 2, 3, 4, 5] it w ou ld be
tr a n sfor m ed to th e list [2, 3, 4, 5, 1]. Modify th e
fu n ction to in clu de a n u m er ic a r g u m en t to specify th e
n u m ber of position s by w h ich left r ota tion is to be
ca r r ied ou t.
6 . Wr ite a pr og r a m th a t defin es a cla ss Card w h ich ca n be
u sed to in sta n tia te ca r ds w ith a pa r ticu la r r a n k a n d
su it. Cr ea te a n oth er cla ss DeckOfCards for
m a in ta in in g a sor ted list of ca r ds u sin g a m eth od
sortedInsert th a t ta kes a n object of cla ss Card a s a n
in pu t pa r a m eter a n d in ser ts it a t th e su ita ble position
in th e sor ted list.
!
Th is section m a y be skipped w ith ou t loss of con tin u ity .
CHAPTER 13
DATA STRUCTURES I: STACK AND QUEUES
CHAPTER OUTLINE
1 3 .1 Sta cks
1 3 .2 Qu eu es
diction a r y m ea n in g of da ta
da ta str u ctu r es
13.1 STACKS
1. pu sh 5
2. pu sh 10
3. pop
4. pu sh 20
5. pu sh 25
6. pu sh 30
7. pop
8. pop
9. pop
1 0. pop
11. pop
1 . Is St a ck Em pt y
Th e m eth od isEmpty deter m in es w h eth er th e sta ck is
em pty by ch eckin g w h eth er th e len g th of th e list
values is zer o, i.e. w h eth er len(self.values) == 0.
Th e m eth od r etu r n s True if th e sta ck is em pty , a n d
False oth er w ise.
2 . Pu sh a n Object
Th e m eth od push ta kes th e elem en t to be pu sh ed a s a n
in pu t pa r a m eter a n d pu ts it a t th e en d of th e list
values by in v okin g th e m eth od append.
a + (b + c) * (k + (d + e) * (f + g * h))
qu eu e: fir st in , fir st ou t
EXERCISES
F ig . 13.13 Qu eu e
F ig . 13.14 Qu eu e
CHAPTER OUTLINE
1 4 .1 In tr odu ction
14.1 INTRODUCTION
lst.data: 20
lst.next.data: 15
lst.next.next.data: 25
lst.next.next.next: None
1 25
1 15
1 20
>>> print(lst)
20->15->25
str in g r epr esen ta tion of a lin ked list
enqueue: a dd a n elem en t to a qu eu e
deque: delete fr om a qu eu e
The methods isEmpty, getFront, and __str__ are
defined in a manner similar to the corresponding
methods described for the class LinkedStack.
SUMMARY
EXERCISES
F ig . 14.22 Dou b l y l i nk ed l i st
class Node:
def __init__(self, value):
'''
Objective: To initialize an object of
class Node
Input Parameter:
self (implicit parameter) - object of
type Node
Return Value: None
'''
self.data = value
self.next = None
self.prev = None
CHAPTER OUTLINE
1 5 .1 Defin ition s a n d Nota tion s
1 5 .2 Bin a r y Sea r ch Tr ee
Fig. 15.1 A tr ee
r oot: A
in ter n a l n odes: A, B, D, F
lea v es: E, C, H, G
t r ee t er mi nol ogy
>>> inorder(bst)
6 10 15 20 23 30
1 . V isit th e r oot.
2 . Pr eor der tr a v er sa l of th e left su btr ee.
3 . Pr eor der tr a v er sa l of th e r ig h t su btr ee.
>>> preorder(bst)
15 10 6 23 20 30
>>> postorder(bst)
6 10 20 30 23 15
h eig h t of th e tr ee is on e m or e th a n th e m a x im u m of th e
h eig h ts of left a n d r ig h t su btr ee
h eig h t of em pty tr ee or a tr ee com pr isin g on ly on e n ode is
zer o
>>> height(bst)
u se of a w r a pper fu n ction
In the script binarySearchTree (Fig. 15.15), we
present complete code for the binary search tree. Note
that inorderTraversal, postorderTraversal,
preorderTraversal, and treeHeight are wrapper
methods used for nested recursive functions inorder,
postorder, preorder, and height.
Fig. 15.14 Recu r siv e m eth od recurInsertVal
Fig. 15.15 Cla ss BinSearchTree (binarySearchTree.py)
SUMMARY
EXERCISES
CHAPTER OUTLINE
1 6 .1 Pa tter n With in a Pa tter n
1 6 .6 Su du ko
n = boardSize
if Queens configuration already contains n queens
print configuration
else
solveFrom(configuration)
restore the configuration to its initial state
1 . __init__
Th is m eth od cr ea tes a n in sta n ce of cla ss Queens a n d
in itia lizes th e da ta m em ber s boardSize, count
(n u m ber of qu een s), a n d board.
2 . getBoardSize
Th is m eth od r etu r n s th e size of th e ch ess boa r d.
3 . __str__
Th is m eth od r etu r n s str in g r epr esen ta tion of object of
ty pe Queens.
4 . unguarded
Th is m eth od r etu r n s True, if th e cu r r en t ch essboa r d
squ a r e is u n g u a r ded, a n d False oth er w ise. It ch ecks
w h eth er a qu een is g u a r din g th e cu r r en t squ a r e. A s a ll
th e r ow s of th e boa r d h a v in g r ow n u m ber g r ea ter th a n
th e r ow n u m ber of th e cu r r en t squ a r e a r e v a ca n t (n ot
y et occu pied by a qu een ), w e on ly n eed to ch eck
w h eth er a qu een in th e r ow s a bov e th e cu r r en t squ a r e
is g u a r din g th e cu r r en t squ a r e. Th is is a ccom plish ed by
ch eckin g u pper pa r ts of th e colu m n , left dia g on a l, a n d
th e r ig h t dia g on a l for th e cu r r en t squ a r e. Th is
a ppr oa ch is su m m a r ized below :
4 -Queens Problem
Solution No. 1
- Q - -
- - - Q
Q - - -
- - Q -
Solution No. 2
- - Q -
Q - - -
- - - Q
- Q - -
possible m ov es for a kn ig h t
if board[x,y] == 0
else if board[x,y] = i
1 . __init__
Th is m eth od cr ea tes a n in sta n ce of cla ss Knight a n d
in itia lizes th e da ta m em ber s boardSize, moveNum
(n u m ber of m ov es ta ken by th e kn ig h t), solNum (keeps
tr a ck of th e n u m ber of solu tion s ex plor ed), moves
(stor es a ll possible m ov es possible fr om th e cu r r en t
position ), a n d board.
2 . getBoardSize
Th is m eth od r etu r n s th e size of th e ch essboa r d.
3 . __str__
Th is m eth od r etu r n s a str in g r epr esen ta tion of th e
object of ty pe Knight.
4 . possible
Th is m eth od r etu r n s True or False depen din g on
w h eth er th e m ov e to a g iv en position in th e ch essboa r d
is possible. It w or ks in th e follow in g m a n n er :
5 . add
Th e m eth od a ssu m es th a t th e cu r r en t ch essboa r d
squ a r e h a s n ot y et been tr a v er sed by th e kn ig h t. It
pla ces th e kn ig h t a t th e g iv en ch essboa r d position by
m a r kin g it travers ed, i.e. a ssig n in g it th e cu r r en t m ov e
n u m ber a n d in cr em en tin g th e moveNum by 1 to den ote
th e n u m ber of m ov es ta ken so fa r .
6 . remove
Th e m eth od a ssu m es th a t th e kn ig h t h a s tr a v er sed th e
ch essboa r d position (x ,y ). It r em ov es th e kn ig h t fr om
g iv en ch essboa r d position by m a r kin g it untravers ed
(v a lu e zer o), a n d decr em en tin g th e moveNum by 1 to
u pda te th e n u m ber of m ov es ta ken so fa r .
7 . moveFurther
Th is m eth od deter m in es n ex t sequ en ce of m ov es if th e
cu r r en t con fig u r a tion is n ot y et com plete. It w or ks in
th e follow in g m a n n er :
8 . isSolved
Th is m eth od deter m in es w h eth er th e cu r r en t
ch essboa r d con fig u r a tion is com plete, i.e. a ll th e
squ a r es h a v e been tr a v er sed. It w or ks in th e follow in g
m a n n er :
Solution Number: 1
1 6 15 10 21
14 9 20 5 16
19 2 7 22 11
8 13 24 17 4
25 18 3 12 23
Solution Number: 2
1 6 11 18 21
12 17 20 5 10
7 2 15 22 19
16 13 24 9 4
25 8 3 14 23
Solution Number: 3
1 6 11 16 21
12 15 20 5 10
7 2 13 22 17
14 19 24 9 4
25 8 3 18 23
Solution Number: 4
1 6 17 12 21
16 11 20 5 18
7 2 9 22 13
10 15 24 19 4
25 8 3 14 23
Solution Number: 5
1 12 17 6 21
18 5 20 11 16
13 2 9 22 7
4 19 24 15 10
25 14 3 8 23
Solution Number: 6
1 16 11 6 21
10 5 20 15 12
17 2 13 22 7
4 9 24 19 14
25 18 3 8 23
Solution Number: 7
1 18 11 6 21
10 5 20 17 12
19 2 15 22 7
4 9 24 13 16
25 14 3 8 23
Solution Number: 8
1 10 15 6 21
16 5 20 9 14
11 2 7 22 19
4 17 24 13 8
25 12 3 18 23
Solution Number: 9
1 16 5 10 21
6 11 20 15 4
19 2 17 22 9
12 7 24 3 14
25 18 13 8 23
Solution Number: 10
1 12 5 18 21
6 17 20 13 4
11 2 9 22 19
16 7 24 3 14
25 10 15 8 23
1 . Ev er y w om en ca n dida te w h o is pr efer r ed by m a n m to
h is cu r r en t a ssig n m en t w pr efer s h er cu r r en t pa r tn er
ov er th e m a n m.
2 . Ev er y m a n ca n dida te w h o is pr efer r ed by w om a n w to
h er cu r r en t a ssig n m en t m pr efer s h is cu r r en t pa r tn er
ov er th e w om a n w.
freeWomen: list of w om en w h o a r e n ot y et en g a g ed
else
1 . __init__
Th is m eth od cr ea tes a n in sta n ce of cla ss
StableMarriage a n d in itia lizes th e da ta m em ber s
count, menPref, womenPref, freeWomen, engagedMen
a n d engagedWomen.
2 . __str__
Th is m eth od r etu r n s a str in g r epr esen ta tion of th e
object of ty pe StableMarriage.
3 . isStable
Th is m eth od r etu r n s True or False depen din g on
w h eth er th e pa ir in g of g iv en m a n a n d w om a n u n der
con sider a tion in dica tes a sta ble m a r r ia g e. It w or ks in
th e follow in g m a n n er :
1 . For man m, all other women candidate who
are preferred by man m to his current
assignment w, are already married and
prefer their current partners over man
m.
i s t h e gi v en p ai r <m, w> st ab l e?
2 . For woman w, all other men candidate who
are preferred by woman w to her current
assignment m, are either yet not engaged
or prefer their current partners over
woman w. (Candidate men who are not
engaged yet are not considered till
now).
4 . free
Th is m eth od sets fr ee a n en g a g ed pa ir of m a n a n d
w om a n . It a ch iev es th is by a ddin g th e g iv en w om a n to
th e list freeWomen w h o a r e n ot en g a g ed. It a lso u pda tes
diction a r ies engagedMen a n d engagedWomen to r eflect
th a t th ey a r e n o lon g er en g a g ed.
5 . engage
Th is m eth od en g a g es th e g iv en m a n a n d w om a n by
pa ir in g th em . It a ch iev es th is by r em ov in g th e g iv en
w om a n fr om th e list freeWomen. It a lso u pda tes
diction a r ies engagedMen a n d engagedWomen to r eflect
th a t th ey a r e en g a g ed.
6 . findMatching
Th is m eth od fin ds sta ble m a tch in g for th e g iv en m a n .
Stable pairings:
{1: 2, 2: 3, 3: 1}
{1: 1, 2: 2, 3: 3}
{1: 3, 2: 1, 3: 2}
sta ble pa ir in g s
16.6 SUDOKU
else,
Solution:
[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]
SUMMARY
EXERCISES
1 1
1 2 1
1 3 3 1
1 4 6 4 1
F ig . 16.15 Koc h f r ac t al c u r v e
CHAPTER OUTLINE
1 7 .1 2 D Gr a ph ics
1 7 .2 3 D Gr a ph ics
17.1 2D GRAPHICS
cmd
python get-pip.py
cmd
plt.plot(3, 2)
plt.show()
plottin g a poin t
plt.plot(3, 2, 'ro')
plt.plot(3, 2, 'or')
x = [2, 4, 6, 8, 10]
y = [3, 5, 7, 9, 11]
plt.plot(x,y, 'ro')
plt.show()
plt.plot(x, y)
x = [2, 4, 6, 8, 10]
y = [3, 5, 7, 9, 11]
plt.plot(x, y, 'r*--')
plt.show()
sy n ta x of plot fu n ction
plt.plot(y)
y = [3, 5, 7, 9, 11]
plt.show()
plt.ylabel('X * X')
plt.title('X vs X * X')
specify in g x a n d y la bels
plt.grid()
displa y in g a g r id
2 3
For example, let us plot functions f(x) = x and f(x) = x
in the same figure in the interval [a,b] in steps of
step. When we display more than one graph in the
same figure, we need a mechanism to distinguish
between them. For this purpose, we make use of
different colors, width, and style, or a combination of
these as illustrated in the function plotFunctions
(Fig. 17.10). In the script plotLines1, we have chosen
colors red and blue for plotting the functions x**2 and
x**3 respectively. Legends associated with different plot
functions are specified using the keyword label while
invoking the plot function (lines 13 and 14). Finally, we
invoke function legend for displaying the legends for
the two functions being plotted (line 15).
Multiple Plots
Saving Figure
2
Suppose, we wish to plot a graph between x and x , and
save it in a file for future reference, thus, avoiding the
need to re-run the code every time such a figure is
needed. To save a graph in the current directory, we use
the function savefig, for example,
x = range(0,5)
y = [i**2 for i in x]
plt.savefig('xSquare')
Fig. 17.13 Six fu n ction s plotted on differ en t su bg r a ph s in sa m e
fig u r e (see pa g e 5 8 5 for th e colou r im a g e)
17.1.2 Histogram and Pi Chart
range(0,max(data)+2)])
Circle
defa u lt v a lu e of r a diu s: 5
Fig. 17.21 Pr og r a m to dr a w a cir cle (circle.py)
Ellipse
Rectangle
Polygon
Arrow
17.2 3D OBJECTS
Box
Sphere
sphere()
materials.rough)
Ring
ring(axis=(0.5,0,0.9), radius=0.5,\
thickness=0.15)
Cylinder
cylinder(pos=(-2,2,1), axis=(5,0,5),
radius=2)
Arrow
up = (0,10,20))
Cone
cone(pos=(0,-2,0), axis=(0,4,0),radius=2)
Fig. 17.36 Con e (see pa g e 5 8 8 for th e colou r im a g e)
Curve
curve(pos=[(-2,-2,0),(-2,0,1),(0,0,0),
(3,0,0),\
scene.fullscreen = True
Fig. 17.38 Pr og r a m to cr ea te a bou n cin g ba ll
(bouncingBall.py)
Fig. 17.39 Sn a psh ots of bou n cin g ba ll (see pa g e 5 8 8 for th e colou r
im a g e)
SUMMARY
EXERCISES
CHAPTER OUTLINE
1 8 .1 Collectin g In for m a tion fr om Tw itter
1 8 .2 Sh a r in g Da ta Usin g Sockets
get-pip.py>
python get-pip.py
Open Authentication
Note that the keys used in the program are only for
illustration purpose; however, the user is expected to
generate the keys himself and replace them
appropriately in the given code.
>>>
ID: 727494459118653446
Account creation date and time: 2016-05-03
13:46:10
Location: India
No. of followers: 3
No. of friends: 34
ID: 135421739
No. of friends: 79
>>>
Followers:
PeaceAlwaysPARI
ikindlebook
gauravparashari
follow er s
Friends:
gvanrossum
iamsrk_sharukh
DataSciFact
CompSciFact
Delhi_U
htTweets
ndtv
timesofindia
EconomicTimes
msdhoni
BeingSalmanKhan
SrBachchan
imVkohli
sachin_rt
PythonHub
PythonStack
pycoders
pythoncoders
djangoproject
ThePSF
fr ien ds
Tweets:
tw eets
>>>
mySock = socket.socket(socket_family,
socket_type,protocol=0)
T a bl e 18.2 Ser v er socket m eth ods a ssocia ted w ith socket object
mySock
T a bl e 18.3 Clien t socket m eth ods a ssocia ted w ith socket object
mySock
T a bl e 18.4 Gen er a l socket m eth ods
F:\PythonCode\Ch18>python server.py
F:\PythonCode\Ch18>
An Echo Server
F:\PythonCode\Ch18>python serverEcho.py
F:\PythonCode\Ch18>python clientEcho.py
Hello
I love Python
F:\PythonCode\Ch18>
key : a ttr ibu te(s) th a t u n iqu ely iden tify tu ples in a r ela tion
m eta da ta : da ta a bou t da ta
import sqlite3
conn = sqlite3.connect('COLLEGE.db')
cur = conn.cursor()
conn.close()
table_constraints]
);
n o tw o tu ples in a da ta ba se ca n h a v e th e sa m e pr im a r y key
);
);
sy n ta x of INSERT com m a n d
SELECT attribute_list
FROM relation_list;
sy n ta x of SELECT com m a n d
SELECT *
FROM STUDENT;
*: w ild ca r d ch a r a cter , u sed in a n SQL com m a n d a s a
su bstitu te for a ll th e a ttr ibu tes occu r r in g in th e r ela tion (s)
FROM STUDENT;
WHERE cla u se: u sed to specify con dition for selection of tu ples
SELECT *
FROM STUDENT
SELECT attribute_list
FROM relation_list
WHERE condition_list;
sy n ta x of SELECT com m a n d in v olv in g WHERE cla u se
print(row)
sy n ta x of UPDATE com m a n d
UPDATE relation
SET attribute-value_pairs
[WHERE condition_list1];
UPDATE STUDENT
cur.execute('UPDATE STUDENT \
sy n ta x of DELETE com m a n d
[WHERE condition_list1];
Suppose a student with roll number 3 has left the
college. We may delete the information about that
student using the following SQL command:
WHERE RollNum = 3;
The command
deletin g th e ta ble
App cla ss: u sed a s a ba se cla ss for dev elopin g kiv y a pplica tion s
Fig. 18.18 Kiv y A pplica tion th a t displa y s a bu tton (main.py)
title=<Application Title>
author=<Your Name>
orientation=<portrait|landscape>
gateway =
JavaGateway(gateway_parameters=GatewayPara
meters(port=25539))
@echo off
ba tch file
and
Python <CompletePath>\hello.py
are executed in command prompt using start
command followed by parameter cmd. Further, use of
the option /k prevents the application initiated, from
involuntary closure until explicitly closed by the user.
The batch file so created can be run by double-clicking it.
gateway = JavaGateway()
intArray =
gateway.new_array(gateway.jvm.int,2)
intArray[0] = 0
intArray[1] = 1
print(value)
u sin g Ja v a a r r a y in Py th on
0
1
cr ea tin g a Ja v a list in Py th on
['red', 3]
[2, 3, 1] [1, 2, 3]
>>>
in Py th on pr og r a m , set start_call-b a c k _ s e r v e
r a ttr ibu te of Java-Gateway to Tr u e for en a blin g Ja v a
pr og r a m s to in v oke Py th on m eth ods
Fig. 18.36 Ja v a a pplica tion s th a t u ses a m eth od Upda te of Py th on
pr og r a m (List.java)
As shown in the program List (Fig. 18.36), object
lst passed via Python program is received as object op
in Java method ListOperation of class List (line 5).
Note that, for every Python method, an interface
method should be defined in Java. In Fig. 18.37, we have
defined an interface ListManipulationInterface
which declares the method Update.
Updated List:
2 4 6
SUMMARY
EXERCISES
A
a bc m odu le, 3 03
ABCMeta, 3 03
A bstr a ct Ba se Cla sses (A BCs), 3 03
A bstr a ct cla ss, 3 03
A bstr a ct da ta ty pe, 2 5 9
A bstr a ct m eth ods, 3 03
A bstr a ction , 2 7 9
A ccessin g Web Da ta , 5 3 9
A ccessor m eth ods, 2 8 0
A ccessor s, 2 8 0
A ctiv a tion r ecor d, 1 9 1
A ctu a l pa r a m eter s, 3 3
A ddin g m eth ods dy n a m ica lly , 2 8 2
A lia sin g , 1 5 1
A lph a bet, 1 3 7
A n im a tion : bou n cin g ba ll, 5 1 7
A ppen d, 3 5 9
A pplica tion pr og r a m m in g in ter fa ces (A PI), 5 2 2
A r g u m en t, 2 0, 3 3
A r ith m etic oper a tor s, 5
A SCII v a lu es, 6
A sser t sta tem en t, 3 9
A ssig n m en t sta tem en ts, 9 , 1 0
A ssocia tion , 1 0
A ttr ibu te r esolu tion or der , 3 07
A ttr ibu tes, 5 4 1
B
Ba se cla ss, 2 8 5
Bin a r y sea r ch tr ee, 4 1 9
bu ildin g , 4 3 1
tr a v er sa l of, 4 2 2
Bin a r y sea r ch , 3 3 1
Bin a r y tr ee, 4 1 8
h eig h t of a , 4 3 0
Bin din g , 1 0
Bits, 8
Bitw ise oper a tor s, 8
Blockin g fu n ction , 4 8 4
Boolea n (bool), 2 5 0
Boolea n v a lu es, 6
Br ea k poin t, 8 7
break sta tem en t, 7 2
Bu bble sor t, 3 2 0
Bu ild, 5 5 1
Bu ilt-in cla sses, 2 5 0
boolea n (bool), 2 5 0
diction a r y (dict), 2 5 0
floa tin g poin t (float), 2 5 0
in teg er (int), 2 5 0
list, 2 5 0
str in g (str), 2 5 0
tuple, 2 5 0
Bu ilt-in fu n ction , 2 0, 2 7
Bu ilt-in fu n ction s for cla sses, 3 09
Bu ilt-in fu n ction s on str in g s, 1 2 7
C
Ca lled fu n ction , 3 0
Ca llee fu n ction , 3 0
Ca ller fu n ction , 3 0
Ca llin g th e fu n ction , 2 0
Ca r din a lity , 5 4 1
Ch a t a pplica tion s, 5 7 1
Ch ild cla ss, 2 8 5
Cla ss a ttr ibu tes, 2 5 0
Cla ss con str u ctor , 2 5 3
Cla ss in itia lizer , 2 5 3
Cla ss n ode, 3 8 5
Cla sses, 2 5 0
Com m a n d lin e a r g u m en ts, 4 1 –4 2
Com plete bin a r y tr ee, 4 1 8
Com position , 2 0, 2 8 4
Con dition a l ex pr ession , 5 1
Con tin u e sta tem en t, 7 2
Con tr ol str u ctu r es, 4 6 –8 0
Con tr ol str u ctu r es, 7 8
Con v er tin g py th on collection s to Ja v a collection s, 5 6 6
Cr ea te ta ble, 5 4 3
Cr ea tin g a lin ked list of cu bes, 3 8 8
D
Da ta , 2 7 9 , 3 5 7
Da ta defin ition la n g u a g e (DDL), 5 4 1 , 5 4 2
Da ta h idin g , 2 7 9
Da ta m a n ipu la tion la n g u a g e (DML), 5 4 2
Da ta str u ctu r es, 3 5 7
Da ta ba se
con cepts, 5 4 1
cr ea tin g , 5 4 2
loa din g th e, 5 4 5
popu la tin g th e, 5 4 5
Da ta ba se m a n a g em en t sy stem (DBMS), 5 4 0
Da te cla ss, 2 6 5
Debu g g in g , 8 5 –9 5
com m a n ds, 8 8 –8 9
Deep copy , 2 1 0
Defa u lt v a lu es, 3 7
Deg r ee, 5 4 1
Deletion , 1 7 7
Depen den cies, 5 5 0
Dequ eu e, 3 6 9 , 4 1 2
Der iv ed cla ss, 2 8 5
Destr u ctor , 2 5 7
Dev elopin g m obile a pplica tion for a n dr oid, 5 5 0
Dict, 2 5 0
Diction a r y , 1 7 5
in v er ted, 1 7 9
oper a tion s, 1 7 7
Docstring, 4
Dom a in , 5 4 3
E
Ech o ser v er , 5 3 7
else sta tem en t, 7 7
Em pty ex cept cla u se, 2 3 2
Em pty la n g u a g e, 1 3 8
En ca psu la tion , 2 7 9
En qu eu e, 3 6 9 , 4 09
En tity , 5 4 1
Er r or s, 2 2 7
ex ception s, 2 2 8
in den ta tion er r or , 2 2 8
in den ta tion , 2 2 8
IndexError, 2 3 0
NameError, 2 2 8
OSError, 2 3 0
sy n ta x , 2 2 7
TypeError, 2 2 9
ValueError, 2 2 9
ZeroDivisionError, 2 2 9
Esca pe sequ en ces, 2 2
eval fu n ction , 2 0
Ex ception s, 2 2 8
Ex tr a ctin g com m en ts, 1 4 4
F
File, 2 2 1
h a n dlin g , 2 2 1
Fin din g com m on fa ctor s, 1 7 1
Floa tin g poin t (float), 2 5 0
Floa tin g poin t n u m ber s, 2
for loop, 5 8
For m a l pa r a m eter s, 3 3
Fr a cta l, 4 7 1
Fr on t, 3 7 2
Fr on t en d, 3 6 9
Fr u itfu l fu n ction , 3 6
Fu n ction pa r a m eter s, 3 3
Fu n ction (s), 1 9 –4 2
append, 1 5 4
axis, 4 8 9
bu ilt-in , 2 0, 2 7
ca lled, 3 0
ca llee, 3 0
ca ller , 3 0
ca llin g th e, 2 0
com position , 2 0
com pr eh en sion , 1 5 7
copy, 1 7 0, 1 7 9
count, 1 2 7 , 1 5 4 , 1 7 5
decode, 1 3 2
defin ition a n d ca ll, 2 7 –3 8
dump, 2 2 6
encode, 1 3 2
en dsw ith , 1 3 2
eval, 2 0
extend, 1 5 4
filter, 1 6 4
find, 1 2 8
fr om m a th m odu le, 2 5
fr u itfu l, 3 6
fu n ction s, 1 5 7
get, 1 7 8
help, 3 7
index, 1 5 4 , 1 7 5
input, 2 0
insert, 1 5 4 , 1 5 6
in v okin g th e, 2 0
isalnum, 1 3 1
isalpha, 1 3 1
isdigit, 1 3 1
islower, 1 2 9
isspace, 1 3 1
istitle, 1 2 9
isupper, 1 2 9
join, 1 3 1
list, 1 5 4
load, 2 2 7
lstrip, 1 3 0
map, 1 6 4
max, 2 4
min, 2 4
n ested, 5 6
ov er loa din g , 2 7 7
pa r tition , 1 3 0
pop, 1 5 4
pow, 2 4
print, 2 1
readline, 2 2 4
r ecu r siv e, 1 8 8
reduce, 1 6 4
remove, 1 5 4 ,
replace, 1 3 0
reverse, 1 5 6
rfind, 1 2 8
round, 2 2
rstrip, 1 3 0
seek, 2 2 5
show, 4 8 4
sort, 1 5 6
split, 1 3 0
sta r tsw ith , 1 3 2
strip, 1 3 0
su per set test
tuple, 1 7 4
type, 2 2
update, 1 7 8
wrapper, 4 3 8
writelines, 2 2 5
zip, 1 7 4
G
Ga m e of Xs a n d Os, 5 5 0
Globa l fr a m e, 2 9
Globa l n a m es, 1 1 4
Gr a ph ica l pa cka g e, 4 4 5
Gr a ph ics, 4 8 3 –5 1 9
2 D, 4 8 3
3 D, 5 09
a n im a tion , 5 1 7 –5 1 9
a r r ow (2 D), 5 08
a r r ow (3 D), 5 1 4
box , 5 1 0
cir cle, 5 02
con e, 5 1 5
cosin e cu r v e, 5 00
cu r v e, 5 1 6
cy lin der , 5 1 3
ellipse, 5 04
h istog r a m , 4 9 6
pie ch a r t, 4 9 8
poly g on , 5 06
r ecta n g le, 5 05
r in g , 5 1 2
sin e cu r v e, 5 00
sph er e, 5 1 0
H
Ha n dler , 2 3 5
Ha r d-codin g , 2 05
hasattr, 3 09
Hier a r ch ica l in h er ita n ce, 2 9 5
Hilber t cu r v e, 4 7 1
Hom e bu tton , 4 8 6
I
Idle, 1
If con dition a l sta tem en t, 4 6
If-elif-else con dition a l sta tem en t, 5 5
If-else con dition a l sta tem en t, 5 2
Im por tin g u ser -defin ed m odu le, 3 8 –3 9
In den ta tion er r or , 2 2 8
In den ta tion , 2 9
IndexError, 2 3 0
In fin ite loops, 6 4
In fix ex pr ession , 3 6 3
In fix for m , 3 6 3
In h er ita n ce, 2 8 5
h ier a r ch ica l, 2 9 5
m u ltilev el, 2 9 5
m u ltiple, 2 9 9
sin g le, 2 8 6
inner fu n ction , 5 7
In or der tr a v er sa l, 4 2 3
input fu n ction , 2 0
In ser tion sor t, 3 2 6
In sta n ce m eth od, 2 8 0
In teg er (int), 2 5 0
In ter section oper a tion on list, 1 7 1
In v er ted diction a r y , 1 7 9
In v oikin g th e fu n ction , 2 0
isEmpty, 3 6 1
isSubclass, 3 09
Iter a tion , 5 7
Iter a tion of th e loop, 5 8
J
Javabridge, 5 6 3
Jpype, 5 6 3
K
Key , 3 1 6 , 5 4 1
Key w or d a r g u m en ts, 3 8
Key w or ds, 1 3
Kiv y , 5 5 0
a pplica tion , 5 6 2
in sta lla tion , 5 5 0
py th on ch a t a pplica tion u sin g , 5 7 0
L
La n g u a g e, 1 3 7
em pty , 1 3 8
n u ll, 1 3 8
r eg u la r , 1 3 7
La st in fir st ou t (LIFO) a r r a n g em en t, 3 5 8
Left bin a r y su btr ee, 4 1 8
Left-ch ild r ela tion sh ip, 4 1 9
LEGB Ru le, 1 1 4
Lin ea r sea r ch , 3 3 0
Lin ked list, 3 8 4
in ser tion a n d deletion a t th e beg in n in g of, 3 8 8
m a in ta in in g sor ted, 4 00
oper a tion s, 3 9 2
sta ck im plem en ta tion u sin g , 4 05 –4 09
str in g r epr esen ta tion of a , 3 9 9
tr a v er sin g a , 3 9 9
list, 2 5 0
List m a n ipu la tion , 3 1 5 –3 5 4
List objects; copy in g , 1 5 9
Lists, 1 5 0–1 5 2
a s a r g u m en t, 1 5 8
in ter section oper a tion on , 1 7 1
tw o-dim en sion a l, 1 5 2
u n ion oper a tion on , 1 7 1
Loa din g th e da ta ba se, 5 4 5
Log ica l oper a tor s, 6
Loop, 5 8
for, 5 8
in fin ite, 6 4
iter a tion of th e, 5 8
n ested, 6 9
while, 6 3
M
Ma ster da ta , 2 4 0
Ma tplotlib, 4 4 5 , 4 8 4
max fu n ction , 2 4
Mem ber sh ip, 1 2 7
Mem or y m a p, 3 4
Meta da ta , 5 4 2
Meth od ov er r idin g , 2 8 9
min fu n ction , 2 4
Modifier , 2 8 0
Modu la r a ppr oa ch , 1 9
Modu le, 1 4
Modu lu s, 2
Mu ltilev el in h er ita n ce, 2 9 5
Mu ltiple in h er ita n ce, 2 9 9
Mu ltiple plots, 4 9 2
N
Na m e m a n g lin g , 2 7 9
NameError, 2 2 8
Na m es, 1 0
Na m espa ces, 1 1 4
Nested fu n ction , 5 6
Nested if-elif-else con dition a l sta tem en t, 5 5
Nested loops, 6 9
Nestin g , 5 5
New -sty le cla sses, 3 06
Node(s), 3 8 4
deletin g , 3 9 6
in ter n a l, 4 1 7
keep tr a ck of, 3 9 7
r oot, 4 1 6
v a lu e of th e, 4 1 6
Nu ll la n g u a g e, 1 3 8
Nu ll str in g , 1 3 7
O
Object a ttr ibu tes, 2 5 5
Object com position , 2 8 4
Object-or ien ted pr og r a m m in g (OOP), 2 7 2
Objects, 2 , 2 5 0
Open a u th en tica tion (OA u th ), 5 2 2
Oper a n ds, 2
Oper a tor ov er loa din g , 2 7 2 , 2 7 3
Oper a tor , 2
a r ith m etic, 5
bitw ise, 8
log ica l, 6
r ela tion a l, 5
OSError, 2 3 0
Ou ter fu n ction , 5 7
P
Pa r a m eter s, 3 3
a ctu a l, 3 3
for m a l, 3 3
fu n ction , 3 3
Pa r en t cla ss, 2 8 5
Pa ss sta tem en t, 7 2
Pa tch es, 5 02
Pa tter n m a tch in g , 1 3 7
Pa tter n w ith in a pa tter n , 4 4 5
Picklin g , 2 2 6
Piv ot elem en t, 3 5 1
Plottin g a poin t, 4 8 4
Poly m or ph ism , 2 7 2
Pop, 3 5 8 , 3 6 1
Popu la tin g th e da ta ba se, 5 4 5
Postfix for m , 3 6 3
Postor der tr a v er sa l, 4 3 0
pow fu n ction , 2 4
Pr eor der tr a v er sa l, 4 2 9
print fu n ction , 2 1
Pr oblem of Tow er of Ha n oi, 2 1 4 –2 1 8
Pr oblem s
eig h t qu een s, 4 4 8
Kn ig h t’s Tou r , 4 5 5
sta ble m a r r ia g e, 4 6 4
Pr og r a m , 1 4
Pr oper ties, 5 5 1
Pseu docode, 3 2
push, 3 5 8 , 3 6 1
Py4j, 5 6 3
Pyjnius, 5 6 3
Pyplot m odu le, 4 8 4
Py th on , 1
a pplica tion s of, 5 2 1 –5 7 6
a r r a y s in , 5 6 5
code, 1
editor , 1
er r or s, 2 2 7
in teg r a tin g ja v a w ith , 5 6 3
sh ell, 2
str in g s, 4 , 1 2 5
sty le, 1 0
tu tor , 1 01
v isu a l, 5 09
Py th on Copy , 2 2 5
Py th on tu tor in ter fa ce, 1 01
Py th on ic sty le, 1 0
Py th on ic w a y , 1 0
Q
Qu eu e, 3 6 9
Qu eu e oper a tion s, 3 7 2
R
raise key w or d, 2 3 6
Ra n dom n u m ber g en er a tion , 2 4 –2 5
Rea r en d, 3 6 9
Recu r sion , 1 8 8 –2 1 8
Recu r siv e fu n ction , 1 8 8
Recu r siv e solu tion s for pr oblem s on lists, 2 04
copy in g a list, 2 09
deep copy , 2 1 0
fla tten a list, 2 04
per m u ta tion , 2 1 1
Recu r siv e solu tion s for pr oblem s on n u m er ic da ta , 1 8 8 –1 9 7
fa ctor ia l, 1 8 8
fibon a cci sequ en ce, 1 9 4
Recu r siv e solu tion s for pr oblem s on str in g s, 1 9 7 –2 04
len g th of a str in g , 1 9 7
pa lin dr om e, 2 01
r ev er sin g a str in g , 1 9 9
Recu sion , 4 8 1
Reg u la r la n g u a g es, 1 3 7
Rela tion , 5 4 1
Rela tion a l oper a tor s, 5
Retr iev in g a ll m a tch in g pa tter n s, 1 4 4
Rev er sin g a str in g , 1 3 6
Rig h t bin a r y su btr ee, 4 1 8
Rig h t-ch ild r ela tion sh ip, 4 1 9
Root n ode, 4 1 6
Rou n d fu n ction , 2 2
S
Sa v in g fig u r e, 4 9 5
Sca la r da ta ty pes, 1 2 3 , 1 5 0
Scope r u le, 2 9 0
Scope, 1 00–1 2 0
Scr ipt m ode, 1 4
Sea r ch in g , 3 1 5 , 3 2 9
Selection sor t, 3 1 6
set fu n ction s, 1 6 7 , 1 7 1
add, 1 6 7
clear, 1 6 7
difference, 1 6 8
intersection, 1 6 8
pop, 1 6 7
remove, 1 6 7
sy m m etr ic_differ en ce, 1 6 8
union, 1 6 8
update, 1 6 7
Sets, 1 6 6
Sh a llow copy , 2 1 0
Sh a r ed session , 1 02
Sh a r in g da ta a cr oss a pplica tion s, 5 3 2
Sh a r in g da ta u sin g sockets, 5 3 2
Sh or t-cir cu it ev a lu a tion , 7
Sh or th a n d n ota tion , 1 1
Sier pin ski Tr ia n g le, 4 7 1
Sin g le in h er ita n ce, 2 8 6
Sin g leton tu ple, 1 7 3
Size, 3 6 1 , 3 7 3
Slice, 1 2 5
Slicin g , 1 2 5 –1 2 6
socket, 5 3 3
Socket pr og r a m m in g , 5 7 0
Sor t
bu bble, 3 2 0
in ser tion , 3 2 6
m er g e, 3 4 9
qu ick, 3 5 1
Sor tin g , 3 1 5
Sou r ce code, 1 4
Sou r ce file scr ipt, 1 4
SQLite da ta ba se, 5 4 0
Sta ck fr a m e, 1 9 1
Sta ck, 3 5 7
deletion of a n elem en t fr om a , 3 5 8
in ser tion of a n elem en t in a , 3 5 8
Sta tic m eth od, 2 8 0
Stepw ise r efin em en t m eth od, 1 9
Stepw ise r efin em en t pr ocess, 3 2
Str a ig h t lin e fu n ction s, 4 6
Str ea m , 5 3 0
streamListener, 5 3 0
Str ictly bin a r y tr ee, 4 1 8
Str in g (str), 2 5 0
Str in g , 1 3 7
n u ll, 1 3 7
Str in g s, 1 2 3 –1 4 7
r ev er sin g , 1 3 6
Str u ctu r ed qu er y la n g u a g e (SQL), 5 4 1
Su b, 2 8 5
Su b-pr og r a m s, 1 9
Su bset, 1 7 0
Su doku pu zzle, 4 7 7
Su per cla ss, 2 8 5
Su per set test, 1 7 0
Sy m bols u sed in r eg u la r ex pr ession s, 1 3 9 –1 4 0
Sy n ta x er r or , 2 2 7
T
Ta ble(s)
cr ea tin g , 5 4 2
deletin g , 5 4 9
in ser tin g da ta in to, 5 4 5
r etr iev in g da ta fr om , 5 4 6
u pda tin g da ta in a , 5 4 8
Tem por a r y v a r ia ble, 1 3
Testin g , 8 5
Tic-Ta c-Toe g a m e, 5 5 8
Top, 3 6 1
Tr a n sa ction da ta , 2 4 0
Tr a n sm ission Con tr ol Pr otocol/In ter n et Pr otocol (TCP/IP), 5 3 3
Tr ee, 4 1 6
a n cestor /descen da n t, 4 1 7
h eig h t, 4 1 7
in ter n a l n ode, 4 1 7
lea f, 4 1 7
lev el, 4 1 7
pa th a n d pa th len g th , 4 1 7
siblin g s, 4 1 8
su btr ee, 4 1 8
try…except cla u se, 2 3 0
Tu ple, 1 7 2 , 2 5 0, 5 4 1
Tw eet u pda te, 5 3 0
Tw itter , 5 2 1
collectin g follow er s, fr ien ds, a n d tw eets of a u ser , 5 2 6
collectin g tw eets h a v in g specific w or ds, 5 3 0
collectin g in for m a tion fr om , 5 2 1
da ta a n a ly sis, 5 2 2
open a u th en tica tion , 5 2 3
Tw o-dim en sion a l list, 1 5 2
Ty pe con v er sion , 2 3
type fu n ction , 2 2
TypeError, 2 2 9
U
uix m odu le, 5 5 1
Un der flow con dition , 3 5 8
Un der flow , 3 7 0
Un h a n dled ex ception s, 2 3 0
Un ion oper a tion on list, 1 7 1
Un ion oper a tor , 1 3 8
Un picklin g , 2 2 6
Upda te com m a n d, 5 4 8
User -defin ed cla sses, 2 5 0
V
V a lu e of th e n ode, 4 1 6
ValueError, 2 2 9
V a lu es, 2
V a r ia ble cu r r en t, 4 02
V a r ia bles, 9
V isu a lize ex ecu tion , 1 02
V oid fu n ction , 3 6
W
Web Da ta ; A ccessin g , 5 3 9
Wedg es, 4 9 8
Where cla u se, 5 4 7
while loop, 6 3
Widg ets, 5 5 1
Wr a pper fu n ction , 4 3 8 , 4 4 7
Wr itin g str u ctu r es to a file, 2 2 6
Z
ZeroDivisionError, 2 2 9
Colour Illustrations
Pl a t e 1 Fu n ction plot(3 , 2 )to displa y poin t (3 , 2 )(see pa g e 4 8 5 )
Pl a t e 2 Poin t (3 , 2 ) (see pa g e 4 8 6 )
Pl a t e 18 Recta n g le (see pa g e 5 06 )
Pl a t e 19 Poly g on (see pa g e 5 07 )
Pl a t e 20 Box (see pa g e 5 1 1 )
Pl a t e 21 Sph er e (see pa g e 5 1 1 )
Pl a t e 22 Rin g (see pa g e 5 1 3 )
Pl a t e 23 Cy lin der (see pa g e 5 1 4 )
Pl a t e 24 A r r ow (see pa g e 5 1 5 )
Pl a t e 25 Con e (see pa g e 5 1 6 )
Pl a t e 26 Cu r v e (see pa g e 5 1 7 )
Pl a t e 27 Sn a psh ots of bou n cin g ba ll (see pa g e 5 1 8 )
Editor—Acquis itions : Neh a Goom er
Editor—Production: M. Ba la kr ish n a n
Copy r igh t © 2018 Pea r son In dia Edu ca t ion Ser v ices Pv t .
Lt d
Th is book is sold su bject to th e con dition th a t it sh a ll n ot, by w a y
of tr a de or oth er w ise, be len t, r esold, h ir ed ou t, or oth er w ise
cir cu la ted w ith ou t th e pu blish er ’s pr ior w r itten con sen t in a n y
for m of bin din g or cov er oth er th a n th a t in w h ich it is pu blish ed
a n d w ith ou t a sim ila r con dition in clu din g th is con dition bein g
im posed on th e su bsequ en t pu r ch a ser a n d w ith ou t lim itin g th e
r ig h ts u n der copy r ig h t r eser v ed a bov e, n o pa r t of th is
pu blica tion m a y be r epr odu ced, stor ed in or in tr odu ced in to a
r etr iev a l sy stem , or tr a n sm itted in a n y for m or by a n y m ea n s
(electr on ic, m ech a n ica l, ph otocopy in g , r ecor din g or oth er w ise),
w ith ou t th e pr ior w r itten per m ission of both th e copy r ig h t ow n er
a n d th e pu blish er of th is book.
ISBN 9 7 8 -9 3 -3 2 5 -8 5 3 4 -8
eISBN 9 7 8 -9 3 -5 2 8 -6 6 03 -8
Fir st Im pr ession
Pu blish ed by Pea r son In dia Edu ca tion Ser v ices Pv t. Ltd, CIN:
U7 2 2 00TN2 005 PTC05 7 1 2 8 , for m er ly kn ow n a s Tu tor V ista
Globa l Pv t. Ltd, licen see of Pea r son Edu ca tion in Sou th A sia .
Hea d Office: 1 5 th Floor , Tow er -B, Wor ld Tr a de Tow er , Plot No. 1 ,
Block-C, Sector 1 6 , Noida 2 01 3 01 , Utta r Pr a desh , In dia .
Reg ister ed Office: 4 th Floor , Softw a r e Block, Eln et Softw a r e City ,
TS 1 4 0, Block 2 & 9 , Ra jiv Ga n dh i Sa la i, Ta r a m a n i, Ch en n a i 6 00
1 1 3 , Ta m il Na du , In dia .
Fa x : 08 0-3 04 6 1 003 , Ph on e: 08 0-3 04 6 1 06 0
Website: in .pea r son .com . Em a il:
com pa n y secr eta r y .in dia @pea r son .com
Compos itor: Ma cr oTex Solu tion s, Ch en n a i.
Printed in India.