PIP - End Sem
PIP - End Sem
1 / 24
Contents
1 Introduction
2 IDLE - An Interpreter for Python
3 Python Strings
4 Relational Operators
5 Logical Operators
6 Bitwise Operators
7 Variables and Assignment Statements
8 Keywords
9 Script Mode
10 Summary
2 / 24
Introduction
3 / 24
Introduction (Cont.)
4 / 24
Execution of a Python Program
Normally, when we compile a python program, we cannot see .pyc
file produced by python compiler and the machine code generated
by Python Virtual Machine (PVM). This is done internally in the
memory and the output is finally visible. For example, if our python
program name is first.py, we can use python compiler to compile it
as:
python first.py
In the preceding statement, python is the command for calling the
python compiler. The compiler should convert the first.py file into
its byte code equvalent file first.pyc. Instead of doing this, the
compiler directly displays the output or result. To separately create
.pyc file from the source code, we can use the following command:
python -m py compile first.py
In order to interpret the .pyc file using PVM, the python compiler
can be called using the following command:
python first.cpython-38.pyc
5 / 24
IDLE - An Interpreter for Python
IDLE stands for Integrated Development and Learning
Environment.
Python IDLE comprises Python Shell (An Interactive Interpreter)
and Python Editor (Allows us to work in Script Mode).
While using Python shell, we just need to type Python code at the
iii prompt and press Enter key. For Example:
iii print(’Hello World’)
Hello World
Python shell may also be used as a calculator. For Example:
iii 18+5
23
iii 27//5
5
iii 27.0//5
5.0
iii 27%5
2
6 / 24
IDLE - An Interpreter for Python
We evaluate the foregoing expressions in Python shell. For
Example:
iii 3**2
9
iii 6/3/2 #(6/3)/2
1.0
iii 2**3**2 #2**(3**2)
512
Left associative operators: +, -, *, /, //, %
Right associative operators: **
Precedence of Arithmetic operators are:
7 / 24
IDLE - An Interpreter for Python
While the parentheses have the highest precedence, addition and
subtraction are at the lowest level.
Python complains when it encounters a wrongly formed
expression. For Example
iii 7+3(4+5)
Traceback (most recent call last):
File ”hpyshell#17i”, line 1, in hmodulei
7+3(4+5)
TyeError: ’int’ object is not callable
Similarly, Division by zero is a meaningless operation. For
Example
iii 7/0
Traceback (most recent call last):
File ”hpyshell#18i”, line 1, in hmodulei
7/0
ZeroDivisionError: division by zero
8 / 24
Python Strings
A string is a sequence of characters.
We can enclose a a sequence of characters between single,
double, or triple quotes to specify.
A string enclosed in single quotes may include double quotes
marks and vice versa.
A string enclosed in triple quotes (also known as docstring, i.e.
documentation string) may include both single and double quote
marks and may extend over several lines. For Example
iii ’Hello World’
’Hello World’
iii print(’Hello World’)
Hello World
iii ”””Hello
World”””
”Hello
World”
9 / 24
Python Strings
10 / 24
Relational Operators
Relational Operators are used for comparing two expressions and
yield True or False.
Arithmetic operators have higher precedence than the relational
operators.
12 / 24
Logical Operators
13 / 24
Bitwise Operators
These operators operate on integers interpreted as strings of
binary digits 0 and 1, also called bits, as:
14 / 24
Bitwise Operators
The precedence of operators are as:
15 / 24
Variables and Assignment Statements
16 / 24
Variables and Assignment Statements (Contd..)
Syntax for assignment statement:
variable = expression
Rules for naming variables:
1. A variable must begin with a letter or (Underscore character).
2. A variable may contain any number of letters, digits, or
underscore characters. No other character apart from these is
allowed.
Always use meaningful variables names.
Follow a consistent style in choosing variables.
Examples of not valid variables as:
17 / 24
Variables and Assignment Statements (Contd..)
Python is case-sensitive. For example, age and Age are not
same, different.
More than one variable may refer to the same object.
iii a = 5
iii b = a
iii b
iii a = 7
iii a
The shorthand notation works for all binary mathematical
operators. a = a hoperator i b is equivalent to a hoperator i = b. For
example: a = a + b is equivalent to a + = b.
Multiple assignments in a single statement as:
iii a, b, c = ’how’, ’are’, ’you?’
Assigning same value to multiple variables in a single statement
as:
iii a = b = 0
18 / 24
Keywords
Keywords are the reserved words that are already defined by the
Python for specific uses.
Keywords cannot be used for any other purposes.
Keywords cannot be used for naming objects.
List of Python keywords are as:
19 / 24
Script Mode
When we exit an IDLE session, and start another IDLE session,
we must redo all computations.This is not convenient mode of
operation for most of the computational tasks.
Python provides another way of working called script mode.
In script mode, instructions are written in a file.
A script should have extension .py or .pyw.
For Example:
20 / 24
Script Mode (Contd..)
21 / 24
Summary
Python interpreter executes one expression (command) at a time.
A string is a sequence of characters. To specify a string, we may
use single, double, or triple quotes.
While evaluating a boolean expression involving and operator, the
second sub-expression is evaluated only if the first sub-expression
yields True.
While evaluating an expression involving or operator, the second
sub-expression is evaluated only if the first sub-expression yields
False.
A variable is a name that refers to a value. We may also say that a
variable associates a name with data object such as number,
character, string or Boolean.
A variable name must begin with a letter or .
Python is case-sensitive.
Python programming can be done in an interactive and script
mode.
22 / 24
References
23 / 24
Thank You
Any Questions?
24 / 24
Functions
1 / 23
Contents
1 Introduction
2 Built-in Functions
5 Assert Statement
2 / 23
Introduction
3 / 23
Built-in Functions
Built-in Functions are predefined functions that are already
available in Python.
The function input enables us to accept an input string from the
user without evaluating its value.
The function input continues to read input text from the user until it
encounters a newline. For Example:
iii name = input(’Enter a Name:’)
Enter a Name: Alok
iii name
’Alok’
Here, the string ’Enter a Name:’ specified within the parentheses
is called an argument.
The function eval is used to evaluate the value of a string. For
Example:
iii eval(’15’)
15
iii eval(’15 + 10’)
4 / 23
Built-in Functions (Cont.)
5 / 23
Built-in Functions (Cont.)
6 / 23
Built-in Functions (Cont.)
The input function considers all inputs as strings. Hence, type
conversion is required. For Example:
iii str(123)
’123’
iii float(123)
123.0
iii int(123.0)
123
iii str(123.45)
’123.45’
iii float(’123.45’)
123.45
iii int(’123.45’) //String incompatible for conversion
Traceback (most recent call last):
File ”hpyshell#3i”, line 1, in hmodulei
int(’123.45’)
ValueError: invalid literal for int() with base 10: ’123.45’
7 / 23
Built-in Functions (Cont.)
The functions max and min are used to find maximum and
minimum values respectively; can also operate on string values.
The integer and floating point values are compatible for
comparison; whereas numeric values cannot be compared with
string values. For Example:
iii max(59,80,95.6,95.2)
95.6
iii min(59,80,95.6,95.2)
59
iii max(’hello’, ’how’, ’are’, ’you’)
’you’
iii min(’hello’, ’how’, ’are’, ’you’, ’Sir’)
’Sir’
The function pow(a,b) computes a to the power b.
iii a = pow(2,3)
iii a
8
8 / 23
Built-in Functions (Cont.)
The function random is used to generate a random number in the
range [0,1). Python module random contains this function and
needs to be imported for using it.
Let us agree that player A will play the first turn if the generated
falls in the range [0,0.5), otherwise player B will play as:
if random.random() h 0.5:
print(’Player A plays the first turn.’)
else:
print(’Player B plays the first turn.’)
The math module provides some functions for mathematical
computations.
In order to obtain these functions available for use in script, we
need to import the math module as:
import math
Name of the module, followed by the separator dot, should
precede function name. The math module also defines a constant
math.pi having value 3.141592653589793.
9 / 23
Built-in Functions (Cont.)
10 / 23
Built-in Functions (Cont.)
11 / 23
Built-in Functions (Cont.)
12 / 23
Function Definition and Call
13 / 23
Function Definition and Call (Cont.)
Having developed the function main in the script picture, we would
like to execute it.
To do this, we need to invoke the function main in the following two
steps.
1. In Run menu, click on the option Run Module.
2. Using Python shell, invoke (call) the function main by executing
the following command:
iii main()
We can eliminate the need to call function main explicitly from the
shell, by including in the script picture, the following call to function
main:
if ’ name ’ == ’ main ’:
main()
Python module has a built-in variable called name containing
the name of the module. When the module itself is being run as
the script, this variable name is assigned the string ’ main ’
designating it to be a main module.
14 / 23
Function Definition and Call (Cont.)
15 / 23
Function Definition and Call (Cont.)
16 / 23
Function Definition and Call (Cont.)
17 / 23
Function Definition and Call (Cont.)
18 / 23
Function Definition and Call (Cont.)
Default Parameter Values
The function parameters may be assigned initial values also called
default values.
Function call uses default value, if value for a parameter is not
provided.
Non-default arguments should not follow default arguments in a
function definition.For Example:
def areaRectangle(length, breadth=1):
”’
Purpose : To compute area of rectangle
Input Parameters :
length - int
breadth (default = 1) - int
Return Value: area - int
”’
area = length * breadth
return area
iii areaRectangle(5)
5
iii areaRectangle(5,2)
19 / 23
Function Definition and Call (Cont.)
Keyword Arguments
Python allows us to specify arguments in an arbitrary order in a
function call, by including the parameter names along with
arguments.
The syntax for keyword arguments is:
parameter name = value
indeed, in situations involving a large number of parameters,
several of which may have default values, keyword arguments can
be of great help. For Example:
iii def f(a=2, b=3, c=4, d=5, e=6, f=7, g=8, h=9):
return a+b+c+d+e+f+g+h
iii f(c=10, g=20)
62
20 / 23
Importing User-Defined Module
21 / 23
Assert Statement
22 / 23
References
23 / 23
Control Structures
Lecture 3
1 / 21
Contents
1 Introduction
2 if Conditional Statement
2 / 21
Introduction
3 / 21
if Conditional Statement
if statement allows non-sequential execution depending upon
whether the condition is satisfied.
The general form of if conditional statement is as follows:
if ⟨condition⟩ :
Sequence S of statements to be executed
Here, condition is a Boolean expression which is evaluated at the
beginning of the if statement. If condition evaluates to True, then
the sequence S of statements is executed, and the control is
transferred to the statement following if statement. However, if
condition evaluates to False, then the sequence S of statements is
ignored, and the control is immediately transferred to the
statement.
4 / 21
if Conditional Statement
For Example (Marks to be updated to passMarks based on a
condition):
def moderate(marks, passMarks):
”’
Objective to moderate result by maximum 1 or 2 marks to
acheive passMarks
Input parameters:
marks - int
passMarks - int
Return Value: marks - int
”’
if marks == passMarks-1 or marks == passMarks-2:
marks=passMarks
return marks
def main():
”’
Objective: To moderate marks if a student just misses
pass marks
Input Parameter: None
Return Value: None
”’
passMarks=40
marks = input(’Enter marks:’)
intmarks = int(marks)
moderatedMarks = moderate(intmarks,passMarks)
print(’Moderated marks:’,moderatedMarks)
if name =’ main ’:
main()
5 / 21
if Conditional Statement
For Example:
⟩⟩⟩
Enter marks: 38
Moderated marks: 40
The flowchart of function moderate is as:
6 / 21
if Conditional Statement
The general form of if-else statement is as follows:
if ⟨condition⟩ :
Sequence S1 of statements to be executed
else:
Sequence S2 of statements to be executed
7 / 21
if Conditional Statement
For Example (Program to authenticate user and allow access to
system using if else statement):
def authenticateUser(password):
”’
Objective to authenticate user and allow access to system
Input parameter : password - string
Return Value: message - string
”’
if password == ’magic’:
message=’Login Successful!!\n Welcome to system.’
if password != ’magic’:
message=’ Password mismatch!!\n’
return message
def main():
”’
Objective: To authenticate user
Input Parameter: None
Return Value: None
”’
print(’ \t LOGIN SYSTEM ’)
print(’======================’)
password = input(’Enter Password:’)
intmarks = int(marks)
message = authenticateUser(password)
print(message)
if name =’ main ’:
main()
8 / 21
if Conditional Statement
For Example:
⟩⟩⟩
if password = ’magic’:
message = ’Login Successful !! \n’
else:
message = ’Password mismatch !! \n’
9 / 21
if Conditional Statement
10 / 21
Iteration (for and while statements)
The process of repetitive execution of statement or a sequence of
statements is called a loop.
Execution of a sequence of statements in a loop is known as an
iteration of the loop.
The control statement for is used when we want to execute a
sequence of statements a fixed number of times.
The general form of for statement is as follows:
for variable in sequence :
Sequence S of Statements
Here, variable refers to the control variable. The sequence S of
statements is executed for each value in sequence.
The function call range(1, n+1) generates a sequence of numbers
from 1 to n. In general, range(start, end, increment) produces a
sequence of numbers from start up to end (but not including end)
in steps of increment. If third argument is not specified, increment
is assumed to be 1.
11 / 21
Iteration (for and while statements)
def main():
”’
Objective: To find sum of first n positive integers based on
user input
Input Parameter: None
Return Value: None
”’
n = int(input(’Enter number of terms:’))
total = summation(n)
print(’Sum of first’, n, ’positive integers:’, total )
if name =’ main ’:
main()
12 / 21
Iteration (for and while statements)
13 / 21
Iteration (for and while statements)
if name =’ main ’:
main()
14 / 21
Iteration (for and while statements)
15 / 21
Iteration (for and while statements)
N.T. - For computing the sum of first few natural numbers, the use
of for loop is more elegant and easy as compared to the while
loop.
16 / 21
Iteration (for and while statements)
Example: To print some pictures
Program to print right triangle and inverted triangle:
def rightTriangle(nRows):
”’
Objective: To print right triangle
Input Parameter: nRows - integer value
Return Value: None
”’
for i in range(1, nRows + 1)
print(’ * ’ * i)
def invertedTriangle(nRows):
”’
Objective: To print inverted triangle
Input Parameter: nRows - integer value
Return Value: None
”’
nSpaces = 0
nStars = 2 * nRows - 1
for i in range(1, nRows+1):
print(’ ’ * nSpaces + ’ * ’ * nStars)
nStars -=2
nSpaces +=1
17 / 21
Iteration (for and while statements)
Example: To print some pictures [Cont.]
def main():
”’
Objective: To print right triangle or inverted triangle
depending on user ’s choice
Input Parameter: None
Return Value: None
”’
choice = int(input(’Enter 1 for right triangle.\n’+ ’Enter 2 for inverted triangle.\n’))
assert choice == 1 or choice == 2
nRows = int(input(’Enter no. of rows))
if choice == 1:
rightTriangle(nRows)
else:
invertedTriangle(nRows)
if name =’ main ’:
main()
Output: (a) Right Triangle (b) Inverted Triangle
* *********
** *******
*** *****
**** ***
***** *
18 / 21
Iteration (for and while statements)
Examples of nested control structures
for(...): while (...):
#Sequence of statements S1 #Sequence of statements S1
for(...): while(...):
#Sequence of statements S2 #Sequence of statements S2
#Sequence of statements S3 #Sequence of statements S3
for(...): while (...):
#Sequence of statements S1 #Sequence of statements S1
while(...): for(...):
#Sequence of statements S2 #Sequence of statements S2
#Sequence of statements S3 #Sequence of statements S3
for(...): while (...):
#Sequence of statements S1 #Sequence of statements S1
for(...): for(...):
#Sequence of statements S2 #Sequence of statements S2
while(...): while(...):
#Sequence of statements S3 #Sequence of statements S3
#Sequence of statements S4 #Sequence of statements S4
#Sequence of statements S5 #Sequence of statements S5
19 / 21
Iteration (for and while statements)
20 / 21
References
21 / 21
Debugging
Lecture 4
1 / 14
Contents
1 Introduction
2 Testing
3 Debugging
2 / 14
Introduction
3 / 14
Testing
4 / 14
Testing
For Example (Finding Maximum of Three Numbers):
def max3(n1, n2, n3):
”’
Objective: To find maximum of three numbers
Input Parameters: n1,n2,n3 - numeric values
Return Value: maxNumber - numeric value
”’
maxNumber=0
if n1< n2 :
if n1 > n3:
maxNumber = n1
elif n2 > n3:
maxNumber=n2
else:
maxNumber = n3
return maxNumber
def main():
”’
Objective: To find maximum of three numbers
Input Parameter: None
Return Value: None
”’
n1 = int(input(’Enter first number: ’))
n2 = int(input(’Enter second number: ’))
n1 = int(input(’Enter third number: ’))
maximum = max3(n1,n2,n3)
print(’Maximum number is:’,maximum)
if name =’ main ’:
main()
5 / 14
Testing
The function max3 is intended to return the maximum of three
numbers.Since the input numbers can be either positive or
negative,we may have test cases containing various combina
tions of positive and negative numbers.
We test this script on various permutations of the inputs: 10, 20,
30, namely:
1. 30, 20, 10 4. 20, 30, 10
2. 30, 10, 20 5. 10, 30, 20
3. 20, 10, 30 6. 10, 20, 30
It so turns out that the result obtained is correct for all input
permutations, except for the permutations 20, 10, and 30:
⟩⟩⟩
Enter first number: 20
Enter second number: 10
Enter third number: 30
Maximum number is 0
Thus, a bug persists in the program that needs to be detected
and removed.
6 / 14
Debugging
However, since we know that the bug exists in the function max3,
we may invoke set trace() within the function body.
8 / 14
Debugging
Let us have a look at debugging commands:
Command Explanation
h or help it lists all the availble commands.
h commandName it prints the description about a command.
w or where Prints the stack trace (sequence of function calls currently in
execution, most recent function call being at the beginning).
Also shows the statement to be executed next.
u or up Moves to the stack frame one level up in the stack trace
d or down Moves to the stack frame one level down in the stack trace
s or step Executes the current statement and moves the control to
either next statement, or the function being invoked in the
current statement.
n or next Executes the current statement and moves the control to
the next statement.unlike step command, if a function is
being invoked in the current statement, the invoked function
gets executed completely.
r or return Continue execution until the current function returns.
p expression Prints the value of the specified expression in the
print(expression) current context.
9 / 14
Debugging
Command Explanation
j (jump) lineno Jumps to the given line number for the next statement
to be executed.
l or list List 11 lines in the vicinity of the current statement
b or break Sets the breakpoint at the specified line.Name of the file
[[file : ]] is one of the optional arguments. When the argument
line[func[,cond]] func is used, the breakpoint is set at the first executable
statement of the specified function. The second argument
may be used to denote a condition which must evaluate
to True for setting the breakpoint.
tbreak Similar to break command. However, the break point
[[file : ]] being set is automatically removed once it is reached
line[func[,cond]]
cl or clear Clears the specified breakpoint. In the absence of an
[[file : ]] argument,clears all the breakpoints.
line[func[,cond]]
c or continue Continue execution untill the breakpoint is reached
a or args Prints the argument list of the current function along
with their values.
q or quit Quits from the python debugger
10 / 14
Debugging
11 / 14
Debugging
(pdb)s
> f:\pythoncode \ch04 \max3.py main()
n1= int(input(’Enter first number: ’))
(pdb) n
Enter first number: 20
> f:\pythoncode \ch04 \max3.py main()
n1= int(input(’Enter second number: ’))
(pdb) n
Enter second number: 10
> f:\pythoncode \ch04 \max3.py main()
n1= int(input(’Enter third number: ’))
(pdb) n)
Enter third number: 30
> f:\pythoncode \ch04 \max3.py main()
->maximum = max3(n1,n2,n3)
(pdb) p (n1, n2, n3)
(20,10,30)
12 / 14
Debugging
(pdb) n
> f:\pythoncode \ch04 \max3.py main()
-> print(’Maximum number is’,maximum)
(pdb) n
Maximum number is 0
–Return–
> f:\pythoncode \ch04 \max3.py main() -< None
-> print(’Maximum number is’,maximum)
(pdb) s
–Return–
> f:\pythoncode \ch04 \max3.py <module>()-> None
-> main()
(pdb) q
Traceback (most recent call last):
File ”F:/pythoncode/ch04/max3.py”,27 line 32, in <module >
main()
bdb.BdbQuit
13 / 14
References
14 / 14
Scope
Lecture 5
*Python Programming: A Modular Approach by Sheetal Taneja and Kumar Naveen, Pearson Education India, Inc., 2017
Visualization of Example-I in Python tutor
➢Each object in Python is assigned a unique identifier that can be accessed using the
function id
➢ Visit the following website www.pythontutor.com
➢ Click on Edit this code
➢ Now write the code
➢ Click on Visualize Execution
Example-I (continued)
➢ After clicking on Visualize Execution, a <Print output> box will appear at the right top
Example-I (continued)
➢ To start visualization, we click <Next >. On encountering the main function definition, the global
frame lists the identifier main as shown in the Figure
➢ The red arrow marks the next line to be executed, and the green arrow marks the line just
executed
Example-I (continued)
➢ Now clicking <Next>, it executes the if statement. Clicking <Next> again executes the call to
the function main and the visualizer shows the frame for the main function
Clicking <Next>, it moves the next line pointer to line 2, and its execution shows the creation of
int object 5 having name a. Later, clicking <Next> shows the output of the execution of line 3
in <Print output> box
Example-I (continued)
➢ Next click executes line 4 and the name b is mapped to the int object 5 created earlier
➢ Further click executes line 5 and the output appears in the <Print output> box
Example-I (continued)
➢ Clicking <Next> executes line 6, resulting in creation of a new int object 7 and its mapping to a
➢ Further clicks execute lines 7 and 8 and the output appears in the <Print output> box
Next click shows return value None associated with the function main as it does not return any
value
Explanation of execution for Example-I
➢ Recall that when this program script is executed, Python makes a note of the definition of the
function main in the global frame
➢ Next, on encountering the if statement, Python checks whether the name of the current
module is __main__
➢ This being true, the expression __ name__ == '__main__' evaluates as True, and the
function main gets invoked
➢ Next, the statements in the main function are executed in a sequence
➢ Execution of line 2 creates an int object 5 and assigns it the name a. This object has a unique
object id but can have multiple names as the execution of the script proceeds.
➢ For example, execution of the statement
b = 3 + 2
in line 4 does not generate a new object, but only associates the name b to the int object 5
created earlier
➢ Now, a and b have the same object id. However, execution of line 6 creates an int object 7
and associates it with the name a
The name b continues to be associated with int object 5 created earlier.
*Python Programming: A Modular Approach by Sheetal Taneja and Kumar Naveen, Pearson Education India, Inc., 2017
Object ID for different data types
➢ The general principle is expressed by saying that Python caches or interns small integer objects
(typically, up to 100) for future use. The same may not hold for other forms of data
*Python Programming: A Modular Approach by Sheetal Taneja and Kumar Naveen, Pearson Education India, Inc., 2017
An example
➢ For example, each of the functions f1 and f2 defined in a script may have the
name x
➢ The variable x defined in function f1 may refer to an object of type different from
that of the object associated with variable x in the function f2
*Python Programming: A Modular Approach by Sheetal Taneja and Kumar Naveen, Pearson Education India, Inc., 2017
Scope
The scope rules for names in Python are often summarized as LEGB rule
LEGB stands for local, enclosing, global, and built in
All names defined within the body of a function are local to it
Function parameters are also considered local
If a name is not locally found, Python recursively searches for its definition in
an enclosing scope
Names defined in the Python script but usually outside of any function or
class definition are called global
Python defines some built-in names such as len and abs, which can be
accessed from anywhere in a program
*Python Programming: A Modular Approach by Sheetal Taneja and Kumar Naveen, Pearson Education India, Inc., 2017
Examples
➢ Example1: Note that as the variable a has global scope, it is accessible in function f
➢ Example 2: Note that the name a introduced in line 3 in the function f is local to it
and has associated value 5. Thus defining the value of name a in the function f, does
not affect the value of the global name a.
Examples (continued)
➢ Example 3: In this example, during execution of function g, when the variable a is to be accessed, Python
looks for it in the local scope of function g, as it is not defined in the body of function g, it is searched in
the next enclosing scope, i.e., the scope of function f, where the variable a is indeed defined, and
therefore the value 5 of the variable a in function f gets bound to the occurrence of variable a in the
function g.
➢ Example 4: In this example, the variable a is defined in the body of inner function g. When we attempt to
access the name a in line 5 of the outer function f, Python looks for its definition first inside the body of
function f, as there is no definition of a in the function f, it looks for definition of a in the next available
enclosing scope, which is the global scope. Again, there is no definition of the name a in global name
space, and hence the error message is printed.
Conclusions
Python visualizer is an online tool for visualizing the execution of Python code.
A namespace defines a mapping of names to the associated objects.
Names that appear in global frame outside of the definition of classes,
functions, and objects are called global names, and collectively they define
the namespace called global namespace.
The names introduced in a class, or function are said to be local to it.
The region in a script in which a name is accessible is called its scope.
The scope rules for names in Python are often summarized as LEGB rule
If a name is not locally defined, Python recursively searches for its definition
in an enclosing scope.
Python defines some built-in names such as len and abs which can be
accessed from anywhere in a program.
Strings
Lecture 6
1 / 57
Contents
1 Introduction
2 Slicing
3 Membership
2 / 57
Introduction
3 / 57
Introduction (Cont.)
4 / 57
Introduction (Cont.)
5 / 57
Introduction (Cont.)
⟩⟩⟩ message[15]
Traceback (most recent call last):
File ”⟨pyshell#17⟩”, line 1, in ⟨module⟩
message[15]
IndexError: string index out of range
6 / 57
Introduction (Cont.)
7 / 57
Slicing
8 / 57
Slicing (Cont.)
9 / 57
Membership
10 / 57
Built-in Functions on Strings (Cont.)
Functions Explanation
s.count(str1) counts number of times string str1 occurs in the
string s
s.find(str1) Returns index of the first occurence of the string
str1 in string s, and returns -1 if str1 is not
present in string s
s.rfind(str1) Returns index of the last occurence of string
str1 in string s, and returns -1 if str1 is not
present in string s
s.capitalize(str1) Returns a string that has first letter of the string
s in uppercase and rest of the letters in lower-
case
11 / 57
Built-in Functions on Strings (Cont.)
12 / 57
Built-in Functions on Strings (Cont.)
13 / 57
Built-in Functions on Strings (Cont.)
14 / 57
Built-in Functions on Strings (Cont.)
15 / 57
Built-in Functions on Strings (Cont.)
16 / 57
Built-in Functions on Strings (Cont.)
⟩⟩⟩ ’Encyclopedia’.count(’c’)
2
⟩⟩⟩ colors = ’green, red, blue, red, red, green’
colors.find(’red’)
7
⟩⟩⟩ colors.rfind(’red’)
23
⟩⟩⟩ colors.find(’orange’)
-1
⟩⟩⟩ ’python IS a Language’.capitalize()
’Python is a language’
⟩⟩⟩ ’python IS a PROGRAMMING Language’.title()
’Python Is A Programming Language’
17 / 57
Built-in Functions on Strings (Cont.)
18 / 57
Built-in Functions on Strings (Cont.)
19 / 57
Built-in Functions on Strings (Cont.)
20 / 57
Built-in Functions on Strings (Cont.)
21 / 57
Built-in Functions on Strings (Cont.)
⟩⟩⟩ mobileN = input(’Enter mobile no : ’)
Enter mobile no : 1234567890
⟩⟩⟩ mobileN.isdigit() and len(mobileN) == 10
True
⟩⟩⟩ ’ ’.isspace()
True
⟩⟩⟩ password = input(’Enter password : ’)
Enter password : Kailash107Ganga
⟩⟩⟩ password.isalnum()
True
⟩⟩⟩ password = input(’Enter password : ’)
Enter password : Kailash 107 Ganga
⟩⟩⟩ password.isalnum()
False
⟩⟩⟩ name = ’Ankita Narain Talwar’
⟩⟩⟩ name.endswith(’Talwar’)
True
22 / 57
Built-in Functions on Strings (Cont.)
23 / 57
Counting the Number of Matching Characters in a Pair
of Strings
def nMatchedChar(str1, str2):
”’
Objective: to count number of occurrences of characters in
str1 that are also in str2
Input parameters: str1,str2-string
Return value: count-numeric
”’
temp1 = str1.lower()
temp2 = str2.lower()
count=0
for ch1 in temp1:
#search for ch1 in temp2
for ch2 in temp2:
if ch1==ch2:
count+=1
return count
24 / 57
Counting the Number of Matching Characters in a Pair
of Strings (Cont.)
25 / 57
Counting the Number of Common Characters in a Pair
of Strings
”’
Objective: to count number of occurrences of characters in
two strings
Input parameters: str1,str2-string
Return value: count-numeric
”’
26 / 57
Counting the Number of Common Characters in a Pair
of Strings
27 / 57
Reversing a String
def reverse(str1):
”’
Objective: to reverse a string
Input parameters: str1-string
Return value: reverseStr-reverse of str1- string
”’
reverseStr = ”
for i in range(len(str1)):
reverseStr=str1[i] + reverseStr
return reverseStr
28 / 57
Reversing a String (Cont.)
using recursion
def reverse(str1):
”’
Objective: to reverse a string
Input parameters: str1-string
Return value: reverse of str1- string
”’
if str1 == ”
return str1
else:
return reverse(str1[1:]) + str1[0]
29 / 57
Pattern Matching
30 / 57
Pattern Matching (Cont.)
31 / 57
Pattern Matching (Cont.)
32 / 57
Pattern Matching (Cont.)
33 / 57
Pattern Matching (Cont.)
34 / 57
Pattern Matching (Cont.)
35 / 57
Pattern Matching (Cont.)
36 / 57
Pattern Matching (Cont.)
37 / 57
Pattern Matching (Cont.)
38 / 57
Pattern Matching (Cont.)
39 / 57
Pattern Matching (Cont.)
40 / 57
Pattern Matching (Cont.)
41 / 57
Pattern Matching (Cont.)
42 / 57
Pattern Matching (Cont.)
ˆPython ⟩⟩⟩ string1 = ’Python is a powerful language’
⟩⟩⟩ if(re.search(’ˆPython’, string1))
print(’String starts with python’)
’String starts with python’
ˆpower ⟩⟩⟩ string1 = ’Python is a powerful language’
⟩⟩⟩ if(re.search(’ˆpower’, string1))
print(’String starts with power’)
else:
print(’String does not start with power’)
String does not start with power
powerful$ ⟩⟩⟩ string1 = ’Python is a powerful language’
⟩⟩⟩ if(re.search(’powerful$’, string1))
print(’String ends with powerful’)
else:
print(’String does not ends with powerful’)
String does not ends with powerful
43 / 57
Pattern Matching (Cont.)
44 / 57
Pattern Matching (Cont.)
-[0-9]+\.[0-9]+ ⟩⟩⟩ string1 = ’Decrease in price is -45.89’
⟩⟩⟩ match = re.search(’-[0-9]+\.[0-9]+’, string1))
match.group()
-45.89
\w* ⟩⟩⟩ string1 = ’Python Shell’
⟩⟩⟩ match = re.search(’\w*’, string1))
match.group()
’Python’
\w*\s\w* ⟩⟩⟩ string1 = ’We used Python Shell’
⟩⟩⟩ match = re.search(’\w*\s\w*’, string1))
match.group()
’We used’
.* ⟩⟩⟩ string1 = ’I use **Python**, do you?’
⟩⟩⟩ match = re.search(’.*’, string1))
match.group()
’I use **Python**, do you?’
45 / 57
Pattern Matching (Cont.)
46 / 57
Pattern Matching (Cont.)
47 / 57
Pattern Matching (Cont.)
48 / 57
Pattern Matching (Cont.)
⟩⟩⟩ match.group()
’ram@gmail’
49 / 57
Pattern Matching (Cont.)
’[email protected]’
’[email protected]’
’[email protected]’
’[email protected]’
50 / 57
Pattern Matching (Cont.)
51 / 57
Pattern Matching (Cont.)
52 / 57
Pattern Matching (Cont.)
regular expression to extract all the single line comments
#.*
Example:
⟩⟩⟩ pythonCode = ”’
”””
Python code to add two numbers.
”””
a = 5 #number1
b = 5 #number2
Compute addition of two numbers
c=a+b
”’
⟩⟩⟩ for i in re.finditer(r’(#.*)’, pythonCode):
⟩⟩⟩ print(i.group())
#number1
#number2
#Compute addition of two numbers
53 / 57
Pattern Matching (Cont.)
”””
Python code to add two numbers.
”””
54 / 57
Pattern Matching (Cont.)
55 / 57
References
56 / 57
Thank You
Any Questions?
57 / 57
Mutable and Immutable Objects
Lecture 7
1 / 52
Contents
1 Introduction
2 Lists
3 Sets
4 Tuples
5 Dictionary
2 / 52
Introduction
3 / 52
Lists
4 / 52
Lists (Cont.)
5 / 52
Lists (Cont.)
6 / 52
Lists (Cont.)
7 / 52
Lists (Cont.)
8 / 52
Lists (Cont.)
Often times, we need to take a list as an input from the user. For
this purpose, we use the function input for taking the input from
the user, and subsequently apply the function eval for
transforming the raw string to a list:
iii details = eval(input(’Enter details of Megha: ’))
Enter details of Megha: [’Megha Verma’, ’C-55, Raj Nagar,Pitam
Pura, Delhi - 110034’, 9876543210]
iii details
[’Megha Verma’, ’C-55, Raj Nagar,Pitam Pura, Delhi - 110034’,
9876543210]
9 / 52
Lists (Cont.)
10 / 52
Lists (Cont.)
Operation Example
Multiplicationiii list2 ∗ 2
Operator ∗ [10, 20, 30, 10, 20, 30]
iii list1=list1 + [’Blue’]
Concatenation
iii list1
Operator +
[’Red’, ’Green’, ’Blue’]
Length iii len(list1)
Operator len 3
iii list2[-1]
Indexing
30
iii list2[0:2]
Slicing
[10, 20]
Syntax:
iii list2[0:3:2]
start:end:inc
[10, 30]
iii min(list2)
Function min
10
11 / 52
Lists (Cont.)
Operation Example
iii max(list1)
Function max
’Red’
Function sum(Not defined iii sum(list2)
on strings) 60
iii 40 in list2
Membership operator in
False
Table 1: Summary of operations that can be applied on lists
12 / 52
Lists (Cont.)
13 / 52
Lists (Cont.)
14 / 52
Lists (Cont.)
Function Explanation
L.append(e) Inserts the element e at the end of list L.
L.extend(L2) Inserts the item in the sequence L2 at the
end of elements of the list L.
L.remove(e) Removes the first occurrence of the ele-
ment e from the list L
L.pop(i) Returns the elements from the list L at in-
dex i, while removing it from the list.
L.count(e) Returns count of occurrences of object e in
the list L.
L.index(e) Returns index of an object e, if present in
list.
L.insert(i,e) Inserts element e at index i in list.
L.sort() Sorts the elements of list.
L.reverse() Reverses the order of elements in the list.
Table 2: List functions
15 / 52
Lists (List Comprehension)
16 / 52
Lists (List Comprehension)
17 / 52
Lists (List as Arguments)
1 def listUpdate(a, i, value):
2 ’’’
3 Objective: To change a value at a particular index in list
4 Input Parameters:
5 a - list
6 i - index of the object in the list to be updated
7 value - modified value at index i
8 Return value: None
9 ’’’
10 a[i] = value
11 def main():
12 ’’’
13 Objective: To change a value at a particular index in list
14 Input Parameters: None
15 Return value: None
16 ’’’
17 lst = [10, 20, 30, [40, 50]]
18 listUpdate(lst, 1, 15)
19 print(lst)
20 if __name__==’__main__’:
21 main()
18 / 52
Lists (List as Arguments)
19 / 52
Lists (Copying List Objects)
20 / 52
Lists (Copying List Objects)
21 / 52
Lists (Copying List Objects)
However, the copy function creates a shallow copy i.e. it does not
create copies of the nested objects. Thus, the two lists share the
same nested objects.
list1[2] and list3[2] refer to the same nested list [30, 40].
let us modify list1[2][0] in sub-list list1[2] of list list1 to value 35.
iii list1[2][0] = 35
iii list1
[10, 25, [35, 40]]
iii list3
[10, 20, [35, 40]]
22 / 52
Lists (Copying List Objects)
To create a copy of a list object so that the nested objects (at all
levels) get copied to new objects, we use the function deepcopy of
the copy module:
deepcopy(): To create a copy of a list including copies of the
nested objects at all level
iii import copy
iii list1 = [10, 20, [30, 40]]
iii list4 = copy.deepcopy(list1)
iii list1[2][0] = 35
iii list1
[10, 20, [35, 40]]
iii list4
[10, 20, [30, 40]]
23 / 52
Lambda Expression
24 / 52
map, reduce, and filter Operations on a Sequence
25 / 52
map, reduce, and filter Operations on a Sequence
26 / 52
map, reduce, and filter Operations on a Sequence
27 / 52
map, reduce, and filter Operations on a Sequence
28 / 52
map, reduce, and filter Operations on a Sequence
29 / 52
Sets
30 / 52
Sets
Function Description
S.add(e) Adds the elements to the set S, if not
present already.
S1.update(L1) Add the items in object L1 to the set S1, if
not already present.
S.remove(e) Removes the element e from set S.
S.pop() Removes an element from the set S.
S.clear() Removes all elements from the set S.
S.copy() Creates a copy of the set S.
S1.union(S2) Returns union of the Sets S1 and S2.
S1.intersection(S2) Returns a set containing common ele-
ments of sets S1 and S2.
32 / 52
Sets (Functions)
Function Description
S1.difference(S2) Returns a set containing elements
in set S1 but not in set S2.
S1.symmetric difference(S2) Returns a set containing elements
that are in one of the two sets S1
and S2, but not in both.
Table 3: Set Functions
The operators <=, ==, and >= may be used to check whether a
given set is a subset, equal, or superset of another set.
33 / 52
Sets (Set Comprehension)
34 / 52
Tuples
35 / 52
Tuples
Operation Example
Multiplicationiii t1 ∗ 2
Operator ∗ (’Monday’, ’Tuesday’, ’Monday’, ’Tuesday’)
iii t3=t1 + (’Wednesday’,)
Concatenation
iii t3
Operator +
(’Monday’, ’Tuesday’, ’Wednesday’)
Length iii len(t1)
Operator len 2
iii t2[-2]
Indexing
20
37 / 52
Tuple Operations
Operation Example
Slicing Syntax: iii t1[1:2]
start:end:inc (’Tuesday’, )
iii min(t2)
Function min
10
iii max(t2)
Function max
30
Function sum iii sum(t2)
(not defined on strings) 60
iii ’Friday’ in t1
Membership operator in
False
Table 4: Summary of operations that can be applied on tuples
38 / 52
Functions Tuple and Zip
39 / 52
Functions count and index
Function Explanation
T.count(e) Returns count of occurrences of e in Tuple T
T.index(e) Returns index of first occurrences of e in Tuple T
Table 5: Tuple Functions
40 / 52
Dictionary
41 / 52
Dictionary
iii price = {’tomato’:40, ’cucumber’:30, ’potato’:20,
’cauliflower’:70, ’cabbage’:50, ’lettuce’:40, ’raddish’:30, ’carrot’:20,
’peas’:80}
iii price[’potato’]
20
iii price[’carrot’]
20
iii price.keys()
dict keys([’tomato’, ’cucumber’, ’potato’, ’cauliflower’, ’cabbage’,
’lettuce’, ’raddish’, ’carrot’, ’peas’])
iii price.values()
dict values([40, 30, 20, 70, 50, 40, 30, 20, 80])
iii price.items()
dict items([(’tomato’, 40), (’cucumber’, 30), (’potato’, 20),
(’cauliflower’, 70), (’cabbage’, 50), (’lettuce’, 40), (’raddish’, 30),
(’carrot’, 20), (’peas’,80)])
42 / 52
Dictionary
43 / 52
Dictionary Operations
some operations that can be applied to a dictionary and illustrate
these operations using a dictionary of digit-name pairs:
digits = {0:’Zero’, 1:’One’, 2:’Two’, 3:’Three’, 4:’Four’, 5:’Five’,
6:’Six’, 7:’Seven’, 8:’Eight’, 9:’Nine’}
Operation Examples
Length operator len (number of iii len(digits)
key-value pairs in dictionary) 10
iii digits[1]
Indexing
’One’
iii min(digits)
Function min
0
iii max(digits)
Function max
9
Function sum (assuming keys iii sum(digits)
are compatible for addition) 45
44 / 52
Dictionary Operations
Operation Examples
iii 5 in digits
True
Membership operator in
iii ’Five’ in digits
False
Table 6: Summary of operations that can be applied on dictionaries
45 / 52
Dictionary Operations
46 / 52
Dictionary Functions
Function Explanation
D.items() Returns an object comprising of tuples of
key-value pairs present in dictionary D
D.keys() Returns an object comprising of all keys of
dictionary D
D.values() Returns an object comprising of all values
of dictionary D
D.clear() Removes all key-value pairs from dictio-
nary D
D.get(key, default) For the specified key, the function returns
the associated value. Returns the default
value in the case key is not present in the
dictionary D
D.copy() Creates a shallow copy of dictionary D
D1.update(D2) Adds the key-value pairs of dictionary D2
to dictionary D1
Table 7: Dictionary Functions 47 / 52
Inverted Dictionary
48 / 52
Inverted Dictionary Code
1 def buildInvDict(dict1):
2 ’’’
3 Objective: To construct inverted dictionary
4 Input parameter: dict1: dictionary
5 Return value: invDict: dictionary
6 ’’’
7 invDict = {}
8 for key,values in dict1.items():
9 if value in invDict:
10 invDict[value].append(key)
11 else:
12 invDict[value] = [key]
13 invDict={x:invDict[x] for x in invDict if len(invDict[x]>1)
}
14 return invDict
49 / 52
Inverted Dictionary Code
1 def main():
2 ’’’
3 Objective: To find inverted dictionary
4 Input parameters: None
5 Return value: None
6 ’’’
7 wordMeaning = eval(input(’Enter word meaning dictionary:’))
8 meaningWord = buildInvDict(wordMeaning)
9 print(’Inverted dictionary:\n’, meaningWord)
10
11 # Statements to initiate the call to main function.
12
13 if __name__==’__main__’:
14 main()
50 / 52
References
51 / 52
Thank You
Any Questions?
52 / 52
Recursion
Lecture 8
Department of Computer Science and engineering, ITER
Siksha ‘O’ Anusandhan (Deemed to be University), Bhubaneswar, Odisha, India
1 / 32
Table Of Contents:
1 Introduction
2 Recursion on Numbers
3 Recursion on Strings
4 Recursion on Lists
6 Conclusion
7 References
2 / 32
Introduction
3 / 32
Recursion on Numbers(Example I)
4 / 32
Recursion on Numbers(Example I Continued)
a s s e r t n>= 0
i f n==0 o r n==1:
return 1
else :
return n∗ f a c t o r i a l ( n−1)
d e f main ( ) :
’’’
O b j e c t i v e : To compute f a c t o r i a l o f a number p r o v i d e d by t h e u s e r
I n p u t p a r a m e t e r : None
R e t u r n v a l u e : None
’’’
n = i n t ( i n p u t ( ’ E n t e r t h e number : ’ ) )
result = f a c t o r i a l (n)
print ( ’ F a c t o r i a l of ’ ,n , ’ i s ’ , r e s u l t )
if n a m e == ’ main ’:
main ( )
5 / 32
Recursion on Numbers(Example I Continued)
The following is the recursive tree to get the fatorial of positive integer 4:
6 / 32
Recursion on Numbers(Example II)
7 / 32
Recursion on Numbers(Example II Continued)
def main ( ) :
n = i n t ( i n p u t ( ’ E n t e r t h e number : ’ ) )
p r i n t ( ’Sum o f f i r s t n n a t u r a l numbers i s ’ , sum( n ) )
if n a m e ==’ main ’:
main ( )
8 / 32
Recursion on Numbers(Example III)
0
if n == 0 (Base part)
reverse(n, rev ) = reverse(n//10, rev ∗ 10 + r ) if n > 1 (Inductive part)
where, r = n%10
9 / 32
Recursion on Numbers(Example III Continued)
def main ( ) :
rev = 0
n = i n t ( i n p u t ( ’ E n t e r t h e number : ’ ) )
print ( ’ reverse of ’ ,n , ’ i s ’ , reverse (n , rev ))
if n a m e ==’ main ’:
main ( )
10 / 32
Recursion on Numbers(Example IV)
11 / 32
Recursion on Numbers(Example IV Continued)
Following program finds the GCD of two given numbers x and y:
def GCD( x , y ) :
i f y==0:
return x
else :
r = x%y
x = y
y = r
r e t u r n GCD( x , y )
def main ( ) :
x = i n t ( input ( ’ Enter x : ’ ))
y = i n t ( input ( ’ Enter y : ’ ))
p r i n t ( ’GCD o f ’ , x , ’ and ’ , y , ’ i s ’ ,GCD( x , y ) )
if n a m e ==’ main ’:
main ( )
12 / 32
Recursion on Numbers(Example V)
13 / 32
Recursion on Numbers(Example V Continued)
def main ( ) :
n = i n t ( i n p u t ( ’ E n t e r a number : ’ ) )
p r i n t ( ’ The f i b o n a c c i number a t p l a c e ’ , n , ’ i s ’ , f i b ( n ) )
if n a m e ==’ main ’:
main ( )
14 / 32
Recursion on Numbers(Example V Continued)
15 / 32
Recursion on Strings(Example I)
16 / 32
Recursion on Strings(Example I conitnued)
Following program gives the length of a given string:
def length ( s t r 1 ) :
’’’
O b j e c t i v e : To d e t e r m i n e t h e l e n g t h o f i n p u t s t r i n g
Input parameter : str1 − s t r i n g
Return val ue : numeric
’’’
if s t r 1== ’ ’ :
return 0
else :
r e t u r n 1+ l e n g t h ( s t r 1 [ 1 : ] )
d e f main ( ) :
’’’
O b j e c t i v e : To d e t e r m i n e l e n g t h o f s t r i n g
I n p u t p a r a m e t e r : None
R e t u r n v a l u e : None
’’’
s t r 1 = input ( ’ Enter the s t r i n g : ’ )
result = length ( str1 )
p r i n t ( ’ Length of s t r i n g ’ , s t r 1 , ’ i s ’ , r e s u l t )
if n a m e == ’ main ’:
main ( ) 17 / 32
Recursion on Strings(Example II)
18 / 32
Recursion on Strings(Example II conitnued)
def main ( ) :
s t r 1 = input ( ’ Enter a s t r i n g : ’ )
print ( ’ Reverse of ’ , str1 , ’ i s ’ , r eve rs e ( str1 ))
if n a m e ==’ main ’:
main ( )
19 / 32
Recursion on Strings(Example III)
20 / 32
Recursion on Strings(Example III continued)
d e f main ( ) :
s t r 1 = input ( ’ Enter the s t r i n g : ’ )
ifisPalindrome ( str1 ):
print ( ’ String i s a palindrome . ’ )
else :
p r i n t ( ’ S t r i n g i s not a palindrome . ’ )
if n a m e == ’ main ’:
main ( )
21 / 32
Recursion on Lists(Example I)
22 / 32
Recursion on Lists(Example I continued)
Following program finds the sum of the elements of the given list:
def s u m l s ( l s , n ) :
i f n==0:
return 0
else :
r e t u r n l s [ n−1]+ s u m l s ( l s , n−1)
def main ( ) :
l s = eval ( input ( ’ Enter l i s t elements : ’ ))
n = len ( l s )
p r i n t ( ’Sum o f e l e m e n t s o f l i s t i s ’ , s u m l s ( l s , n ) )
if n a m e ==’ main ’:
main ( )
23 / 32
Recursion on Lists(Example II)
Given a list of lists, the nesting of lists may occur up to any arbitrary
level.
Flattening of a list means to create a list of all data values in the
given list.
The data values in the flattened list appear in the left to right order
of their appearance in the original list, ignoring the nested structure
of the list.
Thus the list [1,[2,[3,4]]] can be flattened to obtain [1,2,3,4].
Following algorithm can be used:
For every element in list 1
if i is not a list
append it to list 2
otherwise flatten the list i
24 / 32
Recursion on Lists(Example II continued)
def main ( ) :
l s 1 = eval ( input ( ’ Enter the l i s t : ’ ))
result = flatten ( ls1 )
print ( ’ Flattened List : ’ , r e s u l t )
if n a m e ==’ main ’:
main ( )
25 / 32
Shallow copy and Deep copy
Simply assigning a list object to another name does not create a copy
of the list; instead, both the names refer to the same list object.
So when a change is made in any of the list it appears in both the
lists.
26 / 32
Shallow copy and Deep copy
Shallow copy
A shallow copy means constructing a new collection object and then
populating it with references to the child objects found in the original.
The copying process does not recurse and therefore won’t create
copies of the child objects themselves
It means that any changes made to a copy of object do reflect in the
original object.
27 / 32
Shallow copy and Deep copy
## Making s h a l l o w copy
import copy
l s 2 = copy . copy ( l s 1 )
p r i n t ( ’ l s 1= ’ , l s 1 )
p r i n t ( ’ l s 2= ’ , l s 2 )
ls2 [1][2] = 0
p r i n t ( ’ l s 1= ’ , l s 1 )
p r i n t ( ’ l s 2= ’ , l s 2 )
28 / 32
Shallow copy and Deep copy
Deep copy
A deep copy means first constructing a new collection object and then
recursively populating it with copies of the child objects found in the
original
In case of deep copy, a copy of object is copied in other object.
It means that any changes made to a copy of object do not reflect in
the original object.
29 / 32
Shallow copy and Deep copy
import copy
l s 2 = copy . d e e p c o p y ( l s 1 )
p r i n t ( ’ l s 1= ’ , l s 1 )
p r i n t ( ’ l s 2= ’ , l s 2 )
ls2 [1][2] = 0
p r i n t ( ’ l s 1= ’ , l s 1 )
p r i n t ( ’ l s 2= ’ , l s 2 )
30 / 32
Conclusion
31 / 32
References
32 / 32
FILES AND EXCEPTIONS
Lecture 9
1 / 51
Contents
1 Introduction
2 File Handling
2 / 51
Introduction
Programs that we have developed so far take data from the user in
an interactive manner.
Such data remain in memory only during the lifetime of the
program.
Often we want to store data permanently, in the form of files that
usually reside on disks, so that it is available as and when
required.
By default, Python provides a standard input file and a standard
output file to deal with the transitory data.
3 / 51
Introduction (Cont.)
The standard input file is read from the keyboard, and the
standard output file is displayed on the screen.
Apart from these standard input/output files, we can also create
files on disks that store data permanently for subsequent use.
Files provides a means to store data permanently.
A file is a stream of bytes, comprising data of interest.
Before performing a read or write operation in a file, we need to
open the file.
4 / 51
File Handling
5 / 51
File Handling (Cont.)
6 / 51
File Handling (Cont.)
7 / 51
File Handling (Cont.)
>>> f.read()
8 / 51
File Handling (Cont.)
The function close also saves a file, which was opened for writing.
To read the contents of the file f, we open the file again, but this
time in read mode
9 / 51
File Handling (Cont.)
(a). f=open(’PYTHON’,’w’)
f.write(’failure is a part of success’)
f = open(’PYTHON’, ’r’)
print(f.read(4))
f.close()
(b). f=open(’PYTHON’,’w’)
f.write(’failure is a part of success’)
f = open(’PYTHON’, ’r’)
print(f.read())
f.close()
The output of (a) is fail and output of program (b) is failure is a
part of success
10 / 51
File Handling (Cont.)
11 / 51
File Handling (Cont.)
The function readlines() reads and returns all the remaining lines
of the file in the form of a list.
>>> f.readlines()
Just like the readlines function discussed above, the function
writelines takes a list of lines to be written in the file as an
argument
>>> f.writelines()
12 / 51
File Handling (Cont.)
f = open(’PYTHON’, ’w’)
description =[’we either choose the pain of discipline \n’, ’or\n’
’the pain of regret\n’]
f.writelines(description)
f.close()
f = open(’PYTHON’, ’r’)
print(f.read())
f.close()
13 / 51
File Handling (Cont.)
14 / 51
File Handling (Cont.)
15 / 51
File Handling (Cont.)
16 / 51
Writing Structures to a File
import pickle
def main():
”’
Objective: To write and read a list and a dictionary to
and from a file
Input Parameter: None
Return Value: None
”’
f=open(’file3’,’wb’)
pickle.dump([’hello’,’world’],f)
pickle.dump(1:’one’, 2:’two’,f)
f.close()
17 / 51
Writing Structures to a File (cont.)
f=open(’file3’,’rb’)
value1=pickle.load(f)
value2=pickle.load(f)
print(value1,value2)
f.close()
if name ==’ main ’:
main()
the output of above programe is:
[’hello’, ’world’] {1: ’one’, 2: ’two’}
dump(): to convert a structure to byte stream and write it to a file
load(): to read a byte stream from a file and convert it back to the
original structure
18 / 51
Errors and Exceptions
19 / 51
Errors and Exceptions(Cont.)
21 / 51
Handling Exceptions using try. . . except
24 / 51
Errors and Exceptions(Cont.)
def main():
”’
Objective: To open a file for reading
Input Parameter : None
Return Value: None
”’
try:
f=open(’Temporary file’, ’r’)
except IOError:
print(’Problem with Input Output.........’)
print(’Program continues smoothly beyond try...except block’)
if name ==’ main ’:
main()
25 / 51
Errors and Exceptions(Cont.)
26 / 51
Errors and Exceptions(Cont.)
import sys
def main():
”’
Objective: To compute price per unit weight of an item
Input Parameter : None
Return Value: None
”’
price=input(’enter price of item purchaged: ’)
weight=input(’Enter weight of item purchaged: ’)
try:
if price==”: price=None
try:
price=float(price)
except ValueError:
print(’Invalid inputs: ValueError’)
if weight==”: weight=None
try:
27 / 51
Errors and Exceptions(Cont.)
try:
weight=float(weight)
except ValueError:
print(’Invalid inputs: ValueError’)
assert price>= 0 and weight>= 0
result=price/weight
except TypeError:
print(’Invalid inputs: ValueError’)
except ZeroDivisionError:
print(’Invalid inputs: ZeroDivisionError’)
except:
print(str(sys.exc info()))
else:
print(’Price per unit weight: ’, result)
if name ==’ main ’:
main()
28 / 51
Errors and Exceptions(Cont.)
31 / 51
File Processing Example
32 / 51
File Processing Example
>>> import sys
>>> def computemoderatemarks(file1,file2,addpercent):
>>> try:
>>> fin=open(file1,’r’)
>>> fout=open(file2,’w’)
>>> except IOError:
>>> print(’problem in opening the file’);sys.exit()
>>> line1=fin.readline()
>>> while(line1!=”):
>>> slist=line1.split(’,’)
>>> try:
>>> rollno=int(slist[0])
>>> name=slist[1]
>>> marks=int(slist[2])
>>> except IndexError:
>>> print(’undefined index’);sys.exit()
33 / 51
File Processing Example
>>> maxmarks=100
>>>
moderatemarks=marks+((addpercent*maxmarks)/100)
>>> if moderatemarks>100:
>>> moderatemarks=100
>>>
fout.write(str(rollno)+’,’+name+’,’+str(moderatemarks)+’\n’)
>>> line1=fin.readline()
>>> fin.close()
>>> fout.close()
34 / 51
File Processing Example
35 / 51
File Processing Example)
36 / 51
File Processing Example)
37 / 51
File Processing Example)
1.Open files empMaster and empmonthly in read mode while
checking for any errors.
2.Open file monthlyWages in write mode while checking for any
errors.
3.Read one line of input(line1) from empMaster
4.while (line1 !=”):
(a) Retrieve value of empID and hrlyWages from the
line1 while checking for any errors.
(b) Read one line of inputs(line2) from enpMonthly.
(c) Retrieve the value of tEmpID and hrsWorked from
line2 while checking for any errors.
(c) check that empID in empMaster and tEmpID in the
empMonthly match
(d) compute monthly wages and write one line of output
in file monthlyWages
(d) Read one line of input(line1) from empMaster.
38 / 51
File Processing Example)
39 / 51
File Processing Example)
40 / 51
File Processing Example)
>>> try:
>>> empID=int(slist[0])
>>> hrlywages=int(slist1[2])
>>> except IndexError:
>>> print(’undefined index’);sys.exis()
>>> except (ValueError, TypeError):
>>> print(’unsuccesssful convertion to int’); sys.exis()
>>> line2=fTrans.readlines()
>>> sList2=line2.split(’,’)
41 / 51
File Processing Example)
>>> try:
>>> tEmpid=int(slist2[0])
>>> hrsworked=int(slist2[1])
>>> except IndexError:
>>> print(’undefined index’);sys.exis()
>>> except (ValueError,TypeError):
>>> print(’unsuccessful conversion to int’);sys.exit()
>>> if empId==tEmpId:
>>> fwages.write(str(empId)+’,’+
. str(hrlywages*hrsworked)+’\n’)
>>> line1=fmaster.readline()
>>> fmaster.close()
>>> ftrans.close()
>>> fwages.close()
42 / 51
File Processing Example)
43 / 51
Conclusion
44 / 51
Conclusion
45 / 51
Conclusion
46 / 51
Conclusion
47 / 51
Conclusion
The exception occurs because of some mistake in the program
that the system cannot detect before executing the code as there
is nothing wrong in terms of the syntax, but leads to a situation
during the program execution that the system cannot handle.
These errors disrupt the flow of the program at a run-time by
terminating the execution at the point of occurrence of the error.
NameError exception occurs whenever a name specified in the
statement is not found globally.
TypeError exception occurs when an operation in an expression is
incompatible with the type of operands.
ValueError exception occurs whenever an invalid argument is
used in a function call.
ZeroDivisionError exception occurs when we try to perform
numeric division in which denominator happens to be zero.
IOError exception occurs whenever there is any error related to
input or output.
48 / 51
Conclusion
49 / 51
References
50 / 51
Any question ?
Any question ?
51 / 51
Lecture:10 Classes I
1 / 21
Contents
1 Classes I
5 Date Class
2 / 21
CLASSES I
3 / 21
Classes and Objects
We have various in-built class in python like str, int, float etc.
’Raman’,’CBSE’ are instances of class str that are assigned to
variable name and board.
Various methods of class can act on objects of class.
Method lower() can be used on object to return all the lowercase
letters of string.
methods are invoked by the object name followed by dot and the
attribute name.
Also, we can invoke class methods by class name followed by dot
operator, method name and object name passed as an argument
for method.
4 / 21
Person-An example of class
class Person:
count=0
5 / 21
About Person
def getName(self):
return self.name
def getDOB(self):
return self.DOB
def getAddress(self):
return self.address
def setName(self,name):
self.name=name
def setDOB(self,DOB):
self.DOB=DOB
6 / 21
Create Class
def setAddress(self,address):
self.address=address
def getCount(self):
return Person.count
7 / 21
Visualisation
8 / 21
Constructor
9 / 21
Destructor
Default Constructor
The default constructor is a simple constructor which doesn’t
accept any arguments.
Its definition has only one argument which is a reference to the
instance being constructed.
Parameterized constructor
Constructor with parameters is known as parameterized
constructor.
The parameterized constructor takes its first argument as a
reference to the instance being constructed known as self and the
rest of the arguments are provided by the programmer.
10 / 21
Destructor
11 / 21
Destructor Cont.
def __del__(self):
’’’
Objective: To be invoked on deletion
of an instance of the class person.
Input parameter:
self(implicit parameter)-object of
type Person
Return Value:None
’’’
print(’Deleted !!’)
Person.count-=1
12 / 21
Class as Abstract Datatype
13 / 21
Cont.
import sys
import os
sys.path.append(’F:\Pythoncode\Ch10’)
from person import person
def main():
print(’*****dir(Person):\n’,dir(Person))
print(’*****Person.__doc__:\n’,Person.__doc__)
print(’*****Person.__module__:\n’,Person.__module__)
14 / 21
Cont.
print(’\n***** id:Person.__doc__:\n’,id(Person.__doc__))
print(’*****id:Person.__module__:\n’,id(Person.__module__))
print(’*****id:p1.__doc__:\n’,id(p1.__doc__))
print(’*****id:p1.__module__:\n’,id(p1.__module__))
print(’*****id:p2.__doc__:\n’,id(p2.__doc__))
print(’*****id:p2.__module__:\n’,id(p2.__module__))
print(’*****id:dir(Person):\n’,id(dir(Person)))
print(’*****id:dir(p1):\n’,id(dir(p1)))
print(’*****id:dir(p2):\n’,id(dir(p2)))
15 / 21
Cont.
print(’\n*****Person.__dict__\n’,Person.__dict__)
print(’\n*****p1.__dict__\n’,p1.__dict__)
print(’\n*****p2.__dict__\n’,p2.__dict__)
if __name__==’__main__’:
main()
16 / 21
Date Class
17 / 21
Date Class Contd.
import sys
class MyDate:
def__init__(self,day=1,month=1,year=2000):
if not(type(day)==int and type(month)==int \\
and type(year)==int):
print(’Invalid data provided for date’)
sys.exit()
if month>0 and month <=12:
self.month=month
else:
print(’Invalid value for month’)
sys.exit()
if year>1900:
self.year=year
else:
print(’Invalid value for year. Year \\
should be greater than 1900.’)
sys.exit()
self.day=self.checkday(day)
18 / 21
Date Class Contd.
def checkday(self,day):
if self.year%400==0 or \\
(self.year%100!=0 and self.year%4==0):
currentYear=[31,29,31,30,31,30,31,31,30,31,30,31]
else:
currenYear=[31,28,31,30,31,30,31,31,30,31,30,31]
if (day>0 and day<=currentYear[self.month-1]):
return day
else:
print(’Invalid value for day’)
sys.exit()
def __str__(self):
if self.day<=9:
day=’0’+str(self.day)
else:
day=str(self.day)
if self.month<=9:
month=’0’+str(self.month)
else:
month=str(self.month)
return day+’-’+month+’-’+str(self.year)
19 / 21
Date Class Contd.
def main():
today=MyDate(3,9,2014)
print(today)
defaultDate=MyDate()
print(defaultDate)
if __name__==’__main__’:
main()
20 / 21
Thank you
Any questions?
21 / 21
Classes II
Chapter 11
1 / 28
Contents
1 Introduction
2 Polymorphism
Operator Overloading
Function Overloading
3 Encapsulation, Data Hiding, and data Abstraction
4 Modifier and Accessor Methods
5 Static Method
6 Adding Methods Dynamically
7 Composition
8 Inheritance
Single Inheritance
Hierarchical Inheritance
Multiple Inheritance
Abstract Methods
Attribute resolution order for Inheritance
9 Built-In functions for classes
2 / 28
Introduction
3 / 28
Polymorphism
Definition
A method/operator may be applied to objects of different types
(classes). This feature of object oriented programming is called
polymorphism.
Example
len(): len function operates on various types of objects such as str,
list, and tuple.
4 / 28
Operator Overloading
5 / 28
Operator Overloading Cont..
6 / 28
Function Overloading
7 / 28
Function Overloading Cont...
8 / 28
Function Overloading Cont...
9 / 28
Encapsulation, Data Hiding, and data Abstraction
10 / 28
Modifier and Accessor Methods
The methods in the class definition that modify the value of one or
more arguments are known as modifiers.
The methods in the class definition that can only access(not
modify) the value of one or more arguments are known as
accessors.
Static Method
An instance method typically defines operations on the data
members of an instance of a class.
Static methods are used for modifying class data members and
do not require passing object as the first parameter.
To tell Python that a method is a static method, the function
decorator @staticmethod precedes the method definition.
11 / 28
Adding Methods Dynamically
Python allows us to add methods dynamically to a class using the
syntax:
< className > . < newMethodName >=<
existingFunctionName >
If we were to associate a method with a particular instance of a
class, we need to import the function MethodType from the
module types. Subsequently, we use the following syntax to add a
method to an instance of a class:
< instance > . < newMethodName >= MethodType(<
existingFunctionName >, < instance >)
Composition
The process of using objects of the other classes as attribute values is
called object composition.
12 / 28
Inheritance
Inheritance is an important feature of object oriented
programming that imparts ability to a class to inherit properties
and behavior of another class.
Class which inherits properties is called drived, sub, or child class
and class from which properties are inherited is called base,
super, or parent class.
Object class is the base class of all classes.
Example: Person is base class of employee. The notion of
inheritance allows us to express the parent–child relationship
among the classes as shown in figure (1).
14 / 28
Single Inheritance
Derived class is like any other class and may serve as base class
for another class derived from it and so on.
Each derived class may define its new attributes. Thus,
inheritance allows us to create a class hierarchy, also called type
hierarchy.
When inheritance involves more than one level of hierarchy such
as A− > B− > C, it is called multilevel inheritance, and
inheritance involving multiple classes deriving from single base
class is known as hierarchical inheritance as shown in figure (2).
Hierarchical inheritance may be combined with multiple and
multilevel inheritance, to yield hybrid inheritance.
17 / 28
Hierarchical Inheritance Cont...
18 / 28
Multiple Inheritance
Subclass derives its attributes from two or more classes then such
inheritance is called multiple inheritance as shown in figure (3).
19 / 28
Abstract Methods
An abstract method in a base class identifies the functionality
that should be implemented by all its subclasses.
The implementation of an abstract method would differ from one
subclass to another, often the method body comprises just a pass
statement.
A class containing abstract methods is called abstract class.
To use Python Abstract Base Classes (ABCs), one needs to
import ABCMeta and abstractmethod from the abc module.
To indicate that a method is abstract it is by preceding its definition
by @abstractmethod (function decorator).
The definition of an abstract class begins with metaclass =
ABCMeta.
Exmaple:
Shape is base class of rectangle and circle and area is abstract
method because area of rectangle and circle is different.
20 / 28
Abstract Methods Cont...
21 / 28
Abstract Methods Cont...
Output of following code is:
Area of ractangle with length = 30 and breadth = 15 is: 450
Area of circle with radius = 5 is: 78.5
1 class circle(Shape):
2 pi = 3.14
3 def __init__ (self, radius):
4 Shape.__init__(self,’circle’)
5 self.radius = radius
6 def area(self):
7 return round(circle.pi*(slef.radius**2),2)
8
9 r = rectangle(30,15)
10 area_rectangle = r.area()
11 print("Area of ractangle with length = 30 and breadth = 15
is: ",area_ractangle)
12 c = circle(5)
13 area_circle = c.area()
14 print("Area of circle with radius = 5 is: ",area_circle)
22 / 28
Attribute resolution order for Inheritance
23 / 28
Attribute resolution order for Inheritance Cont...
The newStyleClasses, class C inherits from classes B1 and B2,
which further inherit from the class A. It is important to point out
that the class C inherits from classes B1 and B2 in the order B1
and B2. The order of resolution would be the object c1 of class
C, class C, class B1, class B2, class A, class object. The output of
this example is 50.
1 class A:
2 test = 20
3
4 class B1(A):
5 pass
6
7 class B2(A):
8 test = 50
9
10 class C(B1,B2):
11 def str (self):
12 return str(self.test)
13 c1 = C()
14 print(c1) 24 / 28
Built-In functions for classes
25 / 28
Built-In functions for classes Cont...
26 / 28
References
27 / 28
Thank You
Any Questions?
28 / 28
List Manipulation
Lecture 12
1 / 38
Contents
1 Introduction
2 Selection sort
3 Bubble sort
4 Insertion sort
5 Linear Search
6 Binary Search
7 Merge Sort
8 Quick Sort
2 / 38
Introduction
3 / 38
Selection Sort
4 / 38
Selection sort (Contd.)
5 / 38
Selection sort (Contd.)
Compare value at index j=1 with the value at index minIndex.
Since ’Sanvi’ is smaller than ’Vijaya’, minIndex will be set equal to
1.
Now we compare the next value which is at index j=2 with the
value at minIndex.
Since ’Ruby’ is smaller than ’Sanvi’, we will set minIndex to 2.
6 / 38
Selection sort (Contd.)
When j=3, ’Zafar’ will be compared with ’Ruby’ (value at minIndex
2).
Since ’Zafar’ is greater than ’Ruby’, the value of minIndex will
remain unchanged.
7 / 38
Selection Sort (Contd.)
8 / 38
Selection Sort Code
1 ’’’Selection Sort’’’
2 def selectionSort(lst):
3 for i in range(0,len(lst)-1):
4 minIndex=i
5 for j in range(i+1,len(lst)):
6 if lst[j]<lst[minIndex]:
7 minIndex=j
8 if minIndex!=i:
9 lst[minIndex],lst[i]=lst[i],lst[minIndex]
10 def main():
11 lst=eval(input(’Enter a list :’))
12 print(’Sorted list :’)
13 selectionSort(lst)
14 print(lst)
15 if __name__==’__main__’:
16 main()
9 / 38
Selection Sort (Contd.)
10 / 38
Bubble Sort
11 / 38
Bubble Sort (Contd.)
In the first pass, the smallest value will move to the front of the list
at index 0; on subsequent passes, it will be ignored.
In the second iteration, we need to sort the remaining list of n-1
values excluding the value at index 0.
After n-1 iterations, the list will be completely sorted, and the
algorithm will halt.
We start at index 5 and keep on comparing adjacent locations in
order to move the smallest name to the beginning of the list.
12 / 38
The steps performed in first iteration are as follows:
13 / 38
Bubble Sort Code
1 def bubbleSort(lst):
2 n=len(lst)-1
3 for i in range(0,n):
4 for j in range(n,i,-1):
5 if lst[j]<lst[j-1]:
6 lst[j],lst[j-1]=lst[j-1],lst[j]
7 def main():
8 lst=eval(input(’Enter the list :’))
9 print(’Sorted list :’)
10 bubbleSort(lst)
11 print(lst)
12 if __name__==’__main__’:
13 main()
14 / 38
Bubble Sort (Modified)
15 / 38
Bubble Sort Code
1 def bubbleSort(lst):
2 n=len(lst)-1
3 for i in range(0,n):
4 swap=False
5 for j in range(n,i,-1):
6 if lst[j]<lst[j-1]:
7 swap=True
8 lst[j],lst[j-1]=lst[j-1],lst[j]
9 if swap==False:
10 break
11 def main():
12 lst=eval(input(’Enter the list :’))
13 print(’Sorted list :’)
14 bubbleSort(lst)
15 print(lst)
16 if __name__==’__main__’:
17 main()
16 / 38
Insertion Sort
17 / 38
Insertion Sort (Contd.)
18 / 38
Insertion Sort (Contd.)
19 / 38
Insertion Sort (Contd.)
Next, we compare the value of the variable temp, i.e. ’Maya’ with
lst[2], i.e., ’Vijaya’.
As ’Maya’ is less than ’Vijaya’, we shift ’Vijaya’ one position right.
The modified list is
20 / 38
Insertion Sort (Contd.)
Next, we compare the value of the variable temp, i.e. ’Maya’ with
lst[1], i.e. ’Sanvi’.
As ’Maya’ is less than ’Sanvi’, we shift ’Sanvi’ one position right.
The modified list is
21 / 38
Insertion Sort (Contd.)
22 / 38
Insertion Sort Code
1 def insertionSort(lst):
2 for i in range(1,len(lst)):
3 temp=lst[i]
4 j=i-1
5 while j>=0 and lst[j]>temp:
6 lst[j+1]=lst[j]
7 j=j-1
8 lst[j+1]=temp
9 def main():
10 lst=eval(input(’Enter a list :’))
11 print(’Sorted list :’)
12 insertionSort(lst)
13 print(lst)
14
15 if __name__==’__main__’:
16 main()
23 / 38
Searching
We will see how to find out whether a data value appears in a list.
For example, given a list of names of students in a class, we wish
to find whether a particular name appears in the list.
We’ll discuss two methods of searching here, Linear search and
Binary search
24 / 38
Linear search
In this method, we scan the list from the beginning till the required
data value is found or the list is exhausted.
This searching technique is known as linear search as the search
process is sequential.
25 / 38
Linear search Code
1 def linearSearch(lst,searchValue):
2 for i in range(0,len(lst)):
3 if lst[i]==searchValue:
4 return i
5 return None
6 def main():
7 lst=eval(input(’Enter a list :’))
8 searchVal=eval(input(’Enter the value to be searched :’))
9 searchResult=linearSearch(lst,searchVal)
10 print(searchVal,’found at index’,searchResult)
11 if __name__==’__main__’:
12 main()
26 / 38
Binary search
27 / 38
Binary search Code
1 def binarySearch(lst,searchValue):
2 low,high=0,len(lst)-1
3 while low<=high:
4 mid=int((low+high)/2)
5 if lst[mid]==searchValue:
6 return mid
7 elif searchValue<lst[mid]:
8 high=mid-1
9 else:
10 low=mid+1
11 return None
12 def isSorted(lst):
13 for i in range(1,len(lst)):
14 if lst[i]<lst[i-1]:
15 return False
16 return True
28 / 38
Binary search Code(Contd.)
1 def main():
2 lst=eval(input(’Enter a sorted list (ascending order) :’))
3 if not(isSorted(lst)):
4 print(’Given list is not sorted’)
5 else:
6 searchVal=eval(input(’Enter the value to be searched :’
))
7 print(searchVal,’found at index’,binarySearch(lst,
searchVal))
8 if __name__==’__main__’:
9 main()
29 / 38
Merge Sort
30 / 38
Test Case
31 / 38
Merge Sort Code
1 def merge(lst1,lst2):
2 sortedList=[]
3 while len(lst1)!=0 and len(lst2)!=0:
4 if lst1[0]<lst2[0]:
5 sortedList.append(lst1[0])
6 lst1.remove(lst1[0])
7 else:
8 sortedList.append(lst2[0])
9 lst2.remove(lst2[0])
10 if len(lst1)==0:
11 sortedList+=lst2
12 else:
13 sortedList+=lst1
14 return sortedList
32 / 38
Merge Sort Code(Contd.)
1 def mergeSort(lst):
2 if len(lst)==0 or len(lst)==1:
3 return lst
4 else:
5 mid=len(lst)//2
6 lst1=mergeSort(lst[:mid])
7 lst2=mergeSort(lst[mid:])
8 return merge(lst1,lst2)
33 / 38
Quick Sort
34 / 38
Quick Sort Code
1 def partition(lst,start,end):
2 pivotElement=lst[end]
3 i=start-1
4 for j in range(start,end):
5 if lst[j]<=pivotElement:
6 i+=1
7 lst[i],lst[j]=lst[j],lst[i]
8 lst[i+1],lst[end]=lst[end],lst[i+1]
9 return i+1
10 def quickSort(lst,start=0,end=None):
11 if end==None:
12 end=len(lst)-1
13 if start<end:
14 splitPoint=partition(lst,start,end)
15 quickSort(lst,start,splitPoint-1)
16 quickSort(lst,splitPoint+1,end)
17 return lst
35 / 38
Test Case
36 / 38
References
37 / 38
Thank You
Any Questions?
38 / 38