BHASIN HARSH_PROBLEM SOLVING AND PYTHON PROGRAMMING
BHASIN HARSH_PROBLEM SOLVING AND PYTHON PROGRAMMING
PROBLEM SOLVING
AND
PYTHON PROGRAMMING
Fundamentals and Applications: NumPy, Pandas and Matplotlib
HARSH BHASIN
Get free access to e-books for 3 Months
Best Selling Textbooks in COMPUTER SCIENCE ENGINEERING
by
Renowned Authors from Prestigious Publishers
PHI
... & many more
LLEGE (DEEM
CO ED
NG T
RI
O
EE
BE
NJAB ENGIN
UNI
VERSITY)
HARSH BHASIN
Machine Learning Consultant
Former Assistant Professor
Department of Computer Science
FMIT, Jamia Hamdard
Delhi
IN INDIA
NEW AGE INTERNATIONAL (P) LIMITED, PUBLISHERS
LONDON • NEW DELHI
•
Copyright © 2022, New Age International (P) Ltd., Publishers
Published by New Age International (P) Ltd., Publishers
First Edition: 2022
GLOBAL OFFICES
• New Delhi NEW AGE INTERNATIONAL (P) LIMITED, PUBLISHERS
7/30 A, Daryaganj, New Delhi-110002, (INDIA), Tel.: (011) 23253472, 23253771
E-mail: [email protected] • Visit us at www.newagepublishers.com
• Chennai 26, Damodaran Street, T. Nagar, Chennai-600 017, Tel.: (044) 24353401
E-mail: [email protected]
• Guwahati Hemsen Complex, Mohd. Shah Road, Paltan Bazar, Near Starline Hotel
Guwahati-781 008, Tel.: (0361) 2513881, E-mail: [email protected]
• Hyderabad 105, 1st Floor, Madhiray Kaveri Tower, 3-2-19, Azam Jahi Road, Near Kumar Theater
Nimboliadda Kachiguda, Hyderabad-500 027, Tel.: (040) 24652456
E-mail: [email protected]
• Kolkata RDB Chambers (Formerly Lotus Cinema) 106A, 1st Floor, S N Banerjee Road
Kolkata-700 014, Tel.: (033) 22273773, E-mail: [email protected]
• Mumbai 142C, Victor House, Ground Floor, N.M. Joshi Marg, Lower Parel, Mumbai-400 013
Tel.: (022) 24927869, 24915415, E-mail: [email protected]
• New Delhi 22, Golden House, Daryaganj, New Delhi-110 002, Tel.: (011) 23262368, 23262370
E-mail: [email protected]
ISBN: 978-81-951755-0-5
C-21-07-12777
Printed in India at Ajit Printing Press, New Delhi.
Typeset at J.R. Enterprises, New Delhi.
Harsh Bhasin
vii
Contents
Preface vii
Acknowledgements ix
Section I
xi
xii Problem Solving and Python Programming
Section II
Procedural Programming
4. Conditional Statements 73–95
4.1 Introduction 73
4.2 ‘If’, if-else and if-elif-else Constructs 74
4.3 The if-elif-else Ladder 81
4.4 Logical Operators 82
4.5 The Ternary Operator 83
4.6 The Get Construct 84
4.7 Examples 85
4.8 Summary 90
Glossary
91
Points to Remember
91
Contents xiii
Exercises
92
Multiple Choice Questions
92
Programming Exercise
95
5. Looping 96–115
5.1 Introduction 96
5.2 While 98
5.3 Patterns 102
5.4 Nesting and Applications of Loops in Lists 107
5.5 Conclusion 111
Glossary
112
Points to Remember
112
Exercises
113
Multiple Choice Questions
113
Programming
115
6. Functions 116–137
6.1 Introduction 116
6.2 Features of a Function 117
6.3 Basic Terminology 118
6.4 Definition and Invocation 118
6.5 Types of Function 122
6.6 Implementing Search 124
6.7 Scope 125
6.8 Recursion 128
6.9 Conclusion 131
Glossary
132
Points to Remember
132
Exercises
132
Multiple Choice Questions
132
Programming Exercise
133
Questions Based on Recursion
134
Theory
134
Extra Questions
134
7. File Handling 138–158
7.1 Introduction 138
7.2 The File Handling Mechanism 139
7.3 The Open Function and File Access Modes 140
7.4 Python Functions for File Handling 142
7.5 Command Line Arguments 145
7.6 Implementation and Illustrations 147
xiv Problem Solving and Python Programming
Section III
Section IV
Objectives
After reading the chapter, the reader should be able to
• Understand the importance of algorithms
• Understand the features of a good algorithm
• Understand the ways of writing an algorithm
• Understand asymptotic notations
• Differentiate between recursive and iterative algorithms
1.1 INTRODUCTION
This chapter introduces problem solving and algorithms. Let us begin our discussion
by understanding the term algorithm. The word algorithm comes from algorithmi,
from the title “Algoritmi De Numero Indorum”, a book written by Muhammad Ibn
Musa Al-Khwarizmi, who was a Persian mathematician. The word was corrupted and
became “Algorism”. Finally, in the 19th century, it became algorithm. Interestingly, the
book stated above was on Indian numerals. Lately, the word algorithm is identified
with any procedure applied to accomplish a given computing task.
Algorithm directs how to solve a problem and there can be many algorithms to
solve the same problem. However, not all of them are effective and efficient. Also, it is
desirable that in the sequence of steps for accomplishing a task, each step should be as
basic as possible. The task should be completed in a finite number of steps. So, a good
algorithm should be finite and each instruction should be unambiguous.
Algorithms are implemented using programming languages. However, designing
an algorithm cannot be automated as it is, an art [1]. Art cannot be automated,but
you can at least learn approaches like Divide and Conquer, Backtracking, Branch and
Bound, Dynamic programming, Greedy approaches etc. Learning these approaches
3
4 Problem Solving and Python Programming
would not only help you in Computer Science but also help in other disciplines like
Computational Biology, Finance etc.
Algorithms are used everywhere, right from your set-top box to the machine that
gathers biometric data. The advancements in the field of algorithms has changed the
life of millions. The page rank algorithm of Larry Page has helped in the creation
of Google, which is a part of our life. The routing algorithms allowed packets to
be transferred from one computer to another via shortest paths, and helped in the
advancement of communication. Likewise, the pre-processing algorithms for MRI
(Magnetic Resonance Imaging) has helped scientists to develop computer aided
techniques for the diagnosis of diseases. The conventional techniques clubbed
together with the latest advancements like Deep Learning have been able to solve
many problems of the society.
Input:
List: L
Length of the list: n
Item to be searched: item
Algorithm: Linear Search
Set i=0;
Set Flag=0;
While (i<n)
{
if (L[i]==item)
{
Print(“Item found at “,i);
Flag=1;
}
i++;
}
if(Flag==0)
{
Print(“Not found”);
}
}
6 Problem Solving and Python Programming
Start
Set Flag=0
Set i=0
Yes No
i<n L[i]==item
No Yes
Flag=1
If Flag==0 Print(‘Found at’,i)
i++
Yes
No
Not found
Stop
Convention Description
// Single line comment
/*…*/ Multiple line comment
{} Block
<variable name> = <value> Assignment
a<b Less than operator
a>b Greater than operator
a <= b Less than or equal to operator
a >= b Greater than or equal to operator
a == b Checking equality
a != b Checking of the values of the two variables are not
equal
&& AND operator
|| OR operator
term. The 4th Fibonacci term can be found by adding the 3rd and the 2nd term. The 3rd
Fibonacci term can be found by adding the 2nd and the first term, both of which are 1.
The process has been depicted in Figure 1.2.
8 Problem Solving and Python Programming
In the program the variable ‘p’ is initialized to 1. The loop runs ‘b’ times and each time
‘a’ is multiplied by ‘p’. It may be stated here, that the syntax and the nitty-gritty of
programming has been introduced in the following chapters. However, the reader can
revisit this section after completing the next two units.
Program
a=int(input('Enter the first number\t'))
b=int(input('Enter the second number\t:'))
p=1
i=1
while (i<=b):
p=p*a
i+=1
print(a, ' to the power of ', b, 'is ',p)
Output:
Enter the first number 2
Enter the second number :10
2 to the power of 10 is 1024
The above task can also be accomplished using recursion. The following formula
can be used to find ‘a’ to the power of ‘b’.
ab = (ab/2)2, if b is even and
ab = (a(b-1)/2)2 × b, if b is odd
The logic has been implemented in the following program. The output follows.
Program
def pow (a, b):
if b==1:
return a
elif b%2==0:
return (pow(a, b/2)**2)
else:
return ((pow(a, int(b/2))**2)*a)
10 Problem Solving and Python Programming
pow(5,1)
pow(5,2)
pow(5,3)
pow(5,4)
Output:
5
25
125
625
3125
Big O: O()
The worst-case behaviour of an algorithm is depicted by the asymptotic upper bound
notation. For any two functions f(n) and g(n)
O(g(n)) = f(n), for all n > 0 and
f(n) ≤ c × g(n)
Omega: Ω()
The best-case behaviour of an algorithm is depicted by the asymptotic lower bound
notation. For any two functions f(n) and g(n)
Ω(g(n)) = f(n), for all n > 0 and
f(n) ≥ c × g(n)
Algorithmic Problem Solving 11
Theta: Θ()
The asymptotically tight bound for a function f(n) can be defined as follows. For any two
functions f(n) and g(n).
θ(g(n)) = f(n), for all n > 0 and
c1× g(n) ≤ f(n) ≤ c2× g(n)
It may also be noted that,
f(n) = O(g(n)) and
f(n) = Ω(g(n))
then,
f(n) = θ(g(n))
1.6 COMPLEXITY
The algorithm should be efficient both in terms of memory and time. That is, an
algorithm should take the least amount of space and time. In order to understand
the concept, let us consider five different algorithms to solve the same problem.
Assume that the number of elements given as input to the algorithm is n. The first
algorithm takes time proportional to n to accomplish the given task (O(n)), the second
algorithm takes time proportional to n2 to do the same task (O(n2)), the third takes
time proportional to n3(O(n3)), the fourth takes time proportional to log(n) (O(log n))
and the fifth takes time proportional to n log(n), that is O(n log n). This implies that,
if the number of elements double, the time taken to accomplish the given task by the
first algorithm would double, by the second algorithm would be four times, the third
algorithm eight times, the increase in time of the fourth would be less than the increase
in the first and the increase in the time by the fifth would be less than the increase in
the second. Therefore, the order of the time complexity would be as follows.
O(log n) < O(n) < O(n log n) < O(n2) < O(n3)
For example, linear search described in the following section takes O(n) time
whereas Binary Search takes O(log n) time. Therefore, Binary Search takes lesser time
as compared to Linear Search. Merge sort and bubble sort are the two most popular
algorithms for sorting. The Merge-Sort takes O(n log n) time and Bubble Sort takes
O(n2) time. Therefore, Merge-sort has lesser time complexity vis-à-vis Bubble sort and
is hence better.
1.7 ILLUSTRATIONS
Having seen the definition, characteristics and notations used for writing an algorithm,
let us now move to some basic examples. This section presents four problems and their
solutions.
12 Problem Solving and Python Programming
Illustration 1.1:
Given a List, L. Write an algorithm to find the minimum valued element in the list.
Solution:
Let the first element of the list be the minimum valued element (‘min’ = L[0]). The list is
scanned from left to right. At any point, if we are able to find an element having value
less than the value stored in ‘min’, the value of that element is stored in the variable
‘min’. The min1 function performs the requisite task.
Algorithm:
def min1(L):
{
min=L[0];
i=0;
while(i<len(L))
{
if(L[i]<min)
{
min=L[i];
}
i+=1;
}
return min;
}
Test:
min([51,12,71,91,13,19])
Output:
12
Get free access to e-books for 3 Months
Best Selling Textbooks in COMPUTER SCIENCE ENGINEERING
by
Renowned Authors from Prestigious Publishers
PHI
... & many more
LLEGE (DEEM
CO ED
NG T
RI
O
EE
BE
NJAB ENGIN
UNI
VERSITY)
IN INDIA
NEW AGE INTERNATIONAL (P) LIMITED, PUBLISHERS
LONDON • NEW DELHI
•