You are on page 1of 37

Problem Solving and

Programming with

Python
ss
re
yP
As per Anna University syllabus - GE8151
sit
er
iv
Un

REEMA THAREJA
Assistant Professor
d

Department of Computer Science


or

Shyama Prasad Mukherji College for Women


University of Delhi
xf
O

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 1 14/06/18 7:49 PM


3
Oxford University Press is a department of the University of Oxford.
It furthers the University’s objective of excellence in research, scholarship,
and education by publishing worldwide. Oxford is a registered trade mark of
Oxford University Press in the UK and in certain other countries.

Published in India by
Oxford University Press
Ground Floor, 2/11, Ansari Road, Daryaganj, New Delhi 110002, India

© Oxford University Press 2018

The moral rights of the author/s have been asserted.

First published in 2018

All rights reserved. No part of this publication may be reproduced, stored in


a retrieval system, or transmitted, in any form or by any means, without the

ss
prior permission in writing of Oxford University Press, or as expressly permitted
by law, by licence, or under terms agreed with the appropriate reprographics

re
rights organization. Enquiries concerning reproduction outside the scope of the
above should be sent to the Rights Department, Oxford University Press, at the

yP
address above.

You must not circulate this work in any other form


sit
and you must impose this same condition on any acquirer.

ISBN-13: 978-0-19-948949-7
er
ISBN-10: 0-19-948949-1
iv

Typeset in Times New Roman


by Ideal Publishing Solutions, Delhi
Un

Printed in India by Repro India Ltd, Navi Mumbai

Cover image: sommthink / Shutterstock


d

Third-party website addresses mentioned in this book are provided


or

by Oxford University Press in good faith and for information only.


Oxford University Press disclaims any responsibility for the material contained therein.
xf
O

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 2 14/06/18 7:49 PM


Preface

Computers are so widely used in our day-to-day lives that imagining a life without them has become almost
impossible. They are not only used by professionals but also by children for interactively learning lessons,
playing games, and doing their homework. Applications of the computer and its users are increasing by
the day. Learning computer and programming basics is a stepping stone to having an insight into how the
machines work. In-depth knowledge of basic computing terminologies and problem solving strategies such as
algorithm, flowchart, and pseudocode are very essential to develop efficient and effective computer programs
that may help solve a user’s problems.

ss
Since computers cannot understand human languages, special programming languages are designed for

re
this purpose. Python is one such language. It is an open-source, easy, high-level, interpreted, interactive,
object-oriented and reliable language that uses English-like words. It can run on almost all platforms

yP
including Windows, Mac OS X, and Linux. Python is also a versatile language that supports development of
a wide range of applications ranging from simple text processing to WWW browsers to games. Moreover,
programmers can embed Python within their C, C++, COM, ActiveX, CORBA, and Java programs to give
sit
'scripting' capabilities to the users.
Python uses easy syntax and short codes as well as supports multiple programming paradigms, including
er

object oriented programming, functional Python programming, and parallel programming models. Hence, it
iv

has become an ideal choice for the programmers and even the novices in computer programming field find it
easy to learn and implement. It has encompassed a huge user base that is constantly growing and this strength
Un

of Python can be understood from the fact that it is the most preferred programming language in companies
such as Nokia, Google, YouTube, and even NASA for its easy syntax and short codes.
d

About the Book


or

This book is designed as a textbook to cater to the requirements of the Python programming course offered to
the first year engineering students of Anna University. The objective of this book is to introduce the students
xf

to the fundamentals of problem solving strategies and the concepts of Python programming language, and
O

enable them to apply these concepts for solving real-world problems.


The book is organized into 10 chapters that provide comprehensive coverage of all the relevant topics using
simple language. It also contains useful annexures to various chapters including for additional information.
Case studies and appendices are also provided to supplement the text.
Programming skill is best developed by rigorous practice. Keeping this in mind, the book provides a
number of programming examples that would help the reader learn how to write efficient programs. These
programming examples have already been complied and tested using Python 3.4.1 version and can be also
executed on Python 3.5 and 3.6 versions. To further enhance the understanding of the subject, there are
numerous chapter-end exercises provided in the form of objective-type questions, review questions, and
programming problems.

Key Features of the Book


The following are the important features of the book:
• Complete coverage of the Problem Solving and Python Programming syllabus offered by Anna University
• Offers simple and lucid treatment of concepts supported with illustrations for easy understanding.
• Contains separate chapters on Strings, Files, Classes, and Exception Handling.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 5 14/06/18 7:49 PM


vi Preface

• Provides numerous programming examples along with their outputs to help students master the art of
writing efficient Python programs.
• Includes notes and programming tips to highlight the important concepts and help readers avoid common
programming errors.
• Offers rich chapter-end pedagogy including plenty of objective-type questions (with answers), review
questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.
• Includes 6 Annexures and 5 appendices covering differences between Python 2.x and 3.x, installing
Python, debugging and testing, iterators, generators, getters, setters, @property, @deleter, Turtle graphics,
plotting graphs, additional illustrative examples, lab exercises, GUI and Web Programming provided to
supplement the text. Exercises are also added at the end of several annexures and appendices.
• Includes lab exercises and additional illustrative examples explained through algorithms and flowcharts
to help readers hone their logical and programming abilities.
• Provides case studies on creating calculator, calendar, hash files, compressing strings and files, image

ss
processing, shuffling a deck of cards, and mail merge that are linked to various chapters to demonstrate the
application of concepts.

re
• Contains 1 solved previous year's question paper and 2 solved model question papers included to help
readers prepare for the semester-end university examinations.

yP
• Point-wise summary and glossary of keyterms to aid quick recapitulation to concepts.
sit
Organization of the Book
The book contains 10 chapters, 6 annexures, 7 case studies, and 5 appendices. The details of the book are
er

presented as follows.
Chapter 1 discusses the various strategies used for problem solving. Topics such as algorithms, flowcharts,
iv

and pseudocodes supported with some illustrative problems are covered in this chapter.
Un

Chapter 2 discusses about programming languages and their evolution through generations. It describes
different programming paradigms, features of OOP, and merits and demerits of object oriented programming
languages. The chapter also gives a comparative study Python and other OOP languages, and highlights the
d

applications of OOP paradigm.


or

Chapter 3 details the history, important features and applications of Python. It also presents the various
building blocks (such as keywords, identifiers, constants variables, operators, expressions, statements and
xf

naming conventions) supported by the language.


O

The chapter is followed 3 annexures – Annexure 1 provides instructions for installing Python. Annexure 2
provides the comparison between Python 2.x and Python 3.x versions. Annexure 3 discusses testing and
debugging of Python programs using IDLE.
Chapter 4 deals with the different types of decision control statements such as selection/ conditional
branching, iterative, break, continue, pass, and else statements.
Case studies 1 and 2 on simple calculator and generating a calendar show the implementation of concepts
discussed in Chapters 3 and 4.
Chapter 5 provides a detailed explanation of defining and calling functions. It also explains the important
concepts such as variable length arguments, recursive functions, modules, and packages in Python.
Annexure 4 explains how functions are objects in Python. Case study 3 on shuffling a deck of cards
demonstrates the concepts of functions as well as recursion.
Chapter 6 unleashes the concept of strings. The chapter lays special focus on the operators used with
strings, slicing operation, built-in string methods and functions, comparing and iterating through strings, and
the string module.
Chapter 7 discusses how data can be stored in files. The chapter deals with opening, processing (like
reading, writing, appending, etc.), and closing of files though a Python program. These files are handled in

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 6 14/06/18 7:49 PM


Preface vii

text mode as well as binary mode for better clarity of the concepts. The chapter also explains the concept of
file, directory, and the os module.
Case studies 4, 5, and 6 on creating a hash file, mail merge, and finding the resolution of an image
demonstrate the applications of concepts related strings and file handling.
Chapter 8 details the different data structures (such as list, tuple, dictionary, sets, etc.) that are extensively
used in Python. It deals with creating, accessing, cloning, ad updating of lists as well as list methods and
functions. It also describes functional programming and creating, accessing, and updating tuples. It also
includes the concepts related to sets, dictionaries, nested lists, nested tuples, nested sets, nested dictionaries,
list comprehensions, and dictionary comprehensions.
Annexure 5 discusses the concepts of iterator and generator.
Chapter 9 introduces the concept of classes, objects, public and private classes, and instance variables. It
also talks about special methods, built-in attributes, built-in methods, garbage collection, class method, and
static method.

ss
Annexure 6 discusses the getter and setter methods as well as @property and @deleter decorators
facilitate data encapsulation in Python.

re
Chapter 10 elucidates the concepts of exception handling that can be used to make your programs robust.
Concepts such as try, except, and finally blocks, raising and re-raising exceptions, built-in and user-defined

yP
exceptions, assertions, and handling invoked functions, used for handling exceptions are demonstrated in
this chapter.
sit
Case study 7 shows how to compress strings and files using exception handling concepts.
The 5 appendices included in the book discuss about additional illustrative examples, lab exercises, GUI
er

programming, usage of Turtle graphics, plotting graphs and web programming in Python.
iv

Online Resources
Un

For the benefit of faculty and students reading this book, additional resources are available online at india.
oup.com/orcs/9780199489497.
d

For Faculty
or

• Solutions manual (for programming exercises)


• Chapter-wise PPTs
xf

• Chapters on Inheritance and Operator Overloading


O

For Students
• Lab exercises
• Test generator
• Projects
• Solutions to find the output and error exercises
• Extra reading material on unit testing in Python, sorting and searching methods, multi-threaded
programming, network programming, event-driven programming and accessing databases using Python

Acknowledgements
The writing of this textbook was a mammoth task for which a lot of help was required from many people.
Fortunately, I have had wholehearted support of my family, friends, and fellow members of the teaching staff
and students at Shyama Prasad Mukherji College, New Delhi.
My special thanks would always go to my parents, Mr Janak Raj Thareja and Mrs Usha Thareja, and
my siblings, Pallav, Kimi, and Rashi, who were a source of abiding inspiration and divine blessings for me.
I am especially thankful to my son, Goransh, who has been very patient and cooperative in letting me realize

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 7 14/06/18 7:49 PM


viii Preface

my dreams. My sincere thanks go to my uncle, Mr B.L. Theraja, for his inspiration and guidance in writing
this book.
I would like to acknowledge the technical assistance provided to me by Mr Mitul Kapoor. I would like to
thank him for sparing out his precious time to help me to design and test the programs.
I would like to express my gratitude to the reviewers for their valuable suggestions and constructive
feedback that helped in improving the book.
Prof. M V S V Kiranmai
University College of Engineering, JNTU Kakinada
Dr Nagender Kumar Suryadevara
Geethanjali College of Engineering and Technology, Hyderabad
Dr Vipul Kumar Mishra
School of Engineering, Bennett University, Greater Noida, U.P.
Dr G Shobha

ss
R V College of Engineering, Bengaluru
Prof. Priyang P Bhatt

re
GH Patel College of Engineering and Technology, Vallabh Vidyanagar, Gujarat

yP
Prof. Karthick Nanmaran
School of Computing, SRM University, Chennai
Prof. Vinu S.
sit
St. Joseph's College of Engineering, Chennai, Tamil Nadu
er

Last but not the least, I would like to thank the editorial team at Oxford University Press, India for their
help and support over the past few years.
iv

Comments and suggestions for the improvement of the book are welcome. Please send them to me at
Un

reemathareja@gmail.com.
Reema Thareja
d
or
xf
O

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 8 14/06/18 7:49 PM


Brief Contents
Preface v
Detailed Contents  x
Road Map to Syllabus  xv

1 Algorithmic Problem Solving 1
2 Introduction to Object Oriented Programming (OOP) 26

ss
3 Basics of Python Programming 46
Annexure 1 — Installing Python 88

re
Annexure 2 — Comparison between Python 2.x and Python 3.x Versions 90
Annexure 3 — Testing and Debugging 93

yP
4 Decision Control Statements 100
Case Study 1 — Simple Calculator 143
sit
Case Study 2 — Generating A Calendar 146
er

5 Functions and Modules 148


Annexure 4 — Functions as Objects 200
iv

Case Study 3 — Shuffling A Deck of Cards 202


Un

6 Python Strings Revisited 203


7 File Handling 250
d

Case Study 4 — Creating a Hash File (or a message digest of a file) 278
or

Case Study 5 — Mail Merge Program 280


Case Study 6 — Finding Resolution of an Image 282
xf

8 Data Structures 283


O

Annexure 5 — Iterator and Generator 353


9 Classes and Objects 361
Annexure 6 — Getters, Setters, @Property, and @Deleter 393
10 Error and Exception Handling 397
Case Study 7 — Compressing String and Files 424

Appendix A — Additional Illustrative Examples and Lab Exercises  425


Appendix B — GUI Programming with tkinter Package  455
Appendix C — Simple Graphics Using Turtle  465
Appendix D — Plotting Graphs in Python  471
Appendix E — CGI/Web Programming Using Python  477
Solved Question Paper (2017/18)  481
Solved Model Question Paper - 1  483
Solved Model Question Paper - 2  485
About the Author  487

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 9 14/06/18 7:49 PM


Detailed Contents
Preface iv
Brief Contents  ix
Road Map to Syllabus  xv

1 Algorithmic Problem Solving  1 2.2.4 Fourth Generation: Very High-


Level Languages 30
1.1 Introduction 1 2.2.5 Fifth Generation Programming
1.2 Algorithms 1 Language 31
1.3 Building Blocks of Algorithm

ss
2.3 Programming Paradigms 32
(Instructions, State, Control Flow, 2.3.1 Monolithic Programming 32

re
Functions) 2 2.3.2 Procedural Programming 32
1.3.1 Different Approaches of 2.3.3 Structured Programming 33

yP
Designing an Algorithm 2 2.3.4 Object Oriented Programming
1.4 Algorithmic Problem Solving (OOP) 34
Steps 3
sit
2.4 Features of Object Oriented
1.5 Simple Strategies and Notations for Programming 35
Developing Algorithms 4
er

2.4.1 Classes 35
1.5.1 Control Structures Used in 2.4.2 Objects 36
iv

Algorithms 4 2.4.3 Method and Message Passing 36


1.5.2 Flowcharts 9
Un

2.4.4 Inheritance  37
1.5.3 Pseudocodes 11 2.4.5 Polymorphism 38
1.5.4 Programming Languages 13 2.4.6 Containership 38
1.6 Illustrative Problems 14
d

2.4.7 Reusability 38
1.6.1 Find Minimum in a List 14
or

2.4.8 Delegation 39
1.6.2 Insert a Card in a List of Sorted 2.4.9 Data Abstraction and
xf

Cards 16 Encapsulation 39
1.6.3 Guess an Integer Number in a 2.5 Merits and Demerits of Object
O

Range 18 Oriented Programming Language 40


1.6.4 Tower of Hanoi 20 2.6 Applications of Object Oriented
Programming 40
2 Introduction to Object Oriented 2.7 Differences Between Popular
Programming (OOP) 26 Programming Languages 41
2.1 Computer Programming and
3 Basics of Python Programming  46
Programming Languages 26
2.2 Generations of Programming 3.1 Features of Python 46
Languages  27 3.2 History of Python 48
2.2.1 First Generation: Machine 3.3 The Future of Python 50
Language  27 3.4 Writing and Executing first Python
2.2.2 Second Generation: Assembly Program 50
Language 28 3.5 Literal Constants 51
2.2.3 Third Generation: High-Level 3.5.1 Numbers 51
Language 29 3.5.2 Strings 53

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 10 14/06/18 7:49 PM


Detailed Contents xi

3.6 Variables and Identifiers  57 4.2.1 If Statement 101


3.7 Data Types  57 4.2.2 If-Else Statement 102
3.7.1 Assigning or Initializing Values to 4.2.3 Nested if Statements 105
Variables  57 4.2.4 If-Elif-Else Statement 105
3.7.2 Multiple Assignment 59 4.3 Basic Loop Structures/Iterative
3.7.3 Multiple Statements on a Single Statements 110
Line 60 4.3.1 While Loop 111
3.7.4 Boolean 60 4.3.2 For Loop 118
3.8 Input Operation 60 4.3.3 Selecting an Appropriate
3.9 Comments 61 Loop 120
3.10 Reserved Words 61 4.4 Nested Loops  127
3.11 Indentation 61 4.5 The Break Statement 130
3.12 Operators and Expressions 62 4.6 The Continue Statement 131

ss
3.12.1 Arithmetic Operators 62 4.7 The Pass Statement 134
3.13.2 Comparison Operators 63 4.8 The Else Statement Used with

re
3.12.3 Assignment and in-Place or Loops 135
Shortcut Operators 64 Case Study 1 — Simple Calculator  143

yP
3.12.4 Unary Operators 65 Case Study 2 — Generating
3.12.5 Bitwise Operators 65 A Calendar  146
sit
3.12.6 Shift Operators 66
3.12.7 Logical Operators 66 5 Functions and Modules  148
er

3.12.8 Membership Operators  67


5.1 Introduction 148
3.12.9 Identity Operators  67
iv

5.1.1 Need for Functions 149


3.12.10 Operators Precedence and
5.2 Function Definition 150
Un

Associativity 68
5.3 Function Call 152
3.13 Expressions in Python 69
5.3.1 Function Parameters 152
3.14 Operations on Strings 69
5.4 Variable Scope and Lifetime 154
d

3.14.1 Concatenation  70
5.4.1 Local and Global Variables 155
or

3.14.2 Multiplication (Or String


5.4.2 Using the Global Statement 156
Repetition)  70
xf

5.4.3 Resolution of Names 158


3.14.3 Slice A String  71
5.5 The Return Statement 159
3.15 Other Data Types  72
O

5.6 More on Defining Functions 161


3.15.1 Tuples  72
5.6.1 Required Arguments 161
3.15.2 Lists  72
5.6.2 Keyword Arguments 161
3.15.3 Dictionary  73
5.6.3 Default Arguments 162
3.16 Type Conversion  73
5.6.4 Variable-Length
Annexure 1 — Installing Python  88
Arguments 164
Annexure 2 — Comparison between
5.7 Lambda Functions or
Python 2.x and Python 3.x
Anonymous Functions 164
Versions 90
5.8 Documentation Strings 168
Annexure 3 — Testing and Debugging  93
5.9 Good Programming Practices 169
5.10 Recursive Functions  174
4 Decision Control Statements  100
5.10.1 Greatest Common
4.1 Introduction to Decision Control Divisor  176
Statements 100 5.10.2 Finding Exponents  177
4.2 Selection/Conditional Branching 5.10.3 The Fibonacci Series  177
Statements 101 5.10.4 Recursion vs Iteration 180

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 11 14/06/18 7:49 PM


xii Detailed Contents

5.11 Modules 181 7 File Handling  250


5.11.1 The From…Import
Statement 182
7.1 Introduction 250
5.11.2 Name of Module 183
7.2 File Path 250
5.11.3 Making Your Own Modules 184
7.3 Types of Files 251
7.3.1 ASCII Text Files 252
5.11.4 The dir() Function 185
7.3.2 Binary Files 252
5.11.5 The Python Module 186
5.11.6 Modules and Namespaces  187
7.4 Opening and Closing Files 253
7.4.1 The open() Function 253
5.12 Packages in Python 189
7.4.2 The File Object Attributes 254
5.13 Standard Library Modules 190
7.4.3 The close() Method 255
5.14 Globals(), Locals(), and
Reload() 190
7.5 Reading and Writing Files 256
7.5.1 write() and writelines()
5.15 Function Redefinition 192
Methods 256

ss
Annexure 4 — Functions as Objects  200
7.5.2 append() Method 256
Case Study 3 — Shuffling A Deck of

re
7.5.3 The read() and readline()
Cards 202
Methods  257

yP
7.5.4 Opening Files Using with
6 Python Strings Revisited  203
Keyword 259
Introduction 203 7.5.5 Splitting Words 260
sit
6.1 Concatenating, Appending, and 7.5.6 Some Other Useful File
Multiplying Strings 204 Methods 261
er

6.2 Strings are Immutable 206 7.6 File Positions 261


iv

6.3 String Formatting Operator  207 7.7 Renaming And Deleting Files 264
6.4 Built-in String Methods And 7.8 Directory Methods 265
Un

Functions 210 7.8.1 Methods From The OS


6.5 Slice Operation 215 Module 268
Case Study 4 — Creating a Hash File (or a
d

6.5.1 Specifying Stride While Slicing


Strings  217 message digest of a file)  278
or

6.6 ord() and chr() Functions 218 Case Study 5 — Mail Merge Program  280
Case Study 6 — Finding Resolution of an
xf

6.7 in and not in Operators 218


6.8 Comparing Strings 219 Image 282
O

6.9 Iterating String 220


6.10 The String Module 226 8 Data Structures  283
6.11 Regular Expressions 229
6.11.1 The match() Function 229
8.1 Sequence 283
6.11.2 The search() Function 230
8.2 Lists 283
8.2.1 Access Values in Lists 284
6.11.3 The sub() Function 231
8.2.2 Updating Values in Lists 284
6.11.4 The findall() and finditer()
8.2.3 Nested Lists 286
Functions 231
8.2.4 Cloning Lists  287
6.11.5 Flag Options 232
8.2.5 Basic List Operations  287
6.12 Metacharacters in Regular
8.2.6 List Methods 288
Expression 233
8.2.7 Using Lists as Stack 291
6.12.1 Character Classes 234
8.2.8 Using Lists as Queues 292
6.12.2 Groups  237
8.2.9 List Comprehensions 293
6.12.3 Application of Regular Expression
8.2.10 Looping in Lists 295
to Extract Email 238

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 12 14/06/18 7:49 PM


Detailed Contents xiii

8.3 Functional Programming 296 8.6.12 List vs Tuple vs Dictionary vs


8.3.1 filter() Function 296 Set 338
8.3.2 map() Function  297 Annexure 5 — Iterator and Generator  353
8.3.3 reduce() Function 298
8.4 Tuple  307 9 Classes and Objects  361
8.4.1 Creating Tuple  307
9.1 Introduction 361
8.4.2 Utility of Tuples 308
9.2 Classes and Objects 361
8.4.3 Accessing Values in a Tuple 308
9.2.1 Defining Classes 361
8.4.5 Deleting Elements in Tuple 309
9.2.2 Creating Objects 362
8.3.4 Updating Tuple 309
9.2.3 Data Abstraction and Hiding
8.4.6 Basic Tuple Operations 310
Through Classes 362
8.4.7 Tuple Assignment 310
9.3 Class Method And Self
8.4.8 Tuples For Returning Multiple
Argument 363

ss
Values 311
9.4 The __init__() Method (The Class
8.3.9 Nested Tuples 312
Constructor) 364

re
8.4.10 Checking The Index: index()
9.5 Class Variables And Object
Method 312

yP
Variables 364
8.4.11 Counting The Elements: count()
9.6 The __del__() Method  367
Method 313
9.7 Other Special Methods 368
sit
8.4.12 List Comprehension and
9.8 Public And Private Data
Tuples 313
Members 369
er

8.4.13 Variable-Length Argument


9.9 Private Methods  370
Tuples 314
iv

9.10 Calling A Class Method From Another


8.4.14 The zip() Function 315
Class Method  371
Un

8.4.16 Advantages of Tuple over


9.11 Built-In Functions To Check, Get, Set,
List  317
And Delete
8.5 Sets 320
Class Attributes  373
d

8.5.1 Creating a Set 320


9.12 Built-In Class Attributes  374
or

8.6 Dictionaries  327


9.13 Garbage Collection (Destroying
8.6.1 Creating a Dictionary 328
Objects)  375
xf

8.6.2 Accessing Values 329


9.14 Class Methods 386
8.6.2 Adding and Modifying an Item in
O

9.15 Static Methods  387


a Dictionary 330
Annexure 6 — Getters, Setters, @Property,
8.6.3 Modifying an Entry 330
and @Deleter 393
8.6.4 Deleting Items 331
8.6.5 Sorting Items in a
10 Error and Exception Handling  397
Dictionary 334
8.6.6 Looping Over a Dictionary 334 10.1 Introduction to Errors and
8.6.7 Nested Dictionaries 334 Exceptions  397
8.6.8 Built-in Dictionary Functions and 10.1.1 Syntax Errors  397
Methods 335 10.1.2 Logic Error 398
8.6.9 Difference between a List and a 10.1.3 Exceptions 398
Dictionary  337 10.2 Handling Exceptions 399
8.6.10 String Formatting With 10.3 Multiple Except Blocks 400
Dictionaries 338 10.4 Multiple Exceptions in a Single
8.6.11 When to Use Which Data Block 401
Structure? 338 10.5 Except Block without Exception 401

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 13 14/06/18 7:49 PM


xiv Detailed Contents

10.6 The else Clause 402 10.11 The finally Block 408


10.7 Raising Exceptions 403 10.12 Pre-Defined Clean–up Action 410
10.8 Instantiating Exceptions 403 10.13 Re-Raising Exception 411
10.9 Handling Exceptions in Invoked 10.14 Assertions in Python 411
Functions 404 Case Study 8 — Compressing String and
10.10 Built-in and User-Defined Files 422
Exceptions 406
Appendix A — Additional Illustrative Examples and Lab Exercises  425
Appendix B — GUI Programming with tkinter Package  455
Appendix C — Simple Graphics using Turtle  465
Appendix D — Plotting Graphs in Python  471
Appendix E — CGI/Web Programming using Python  477
Solved Question Paper (2017/18)  481

ss
Solved Model Question Paper - 1  483

re
Solved Model Question Paper - 2  485
About the Author  487

yP
sit
er
iv
Un
d
or
xf
O

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 14 14/06/18 7:49 PM


CHAPTER
Algorithmic
1 Problem Solving

• Algorithm • Flowchart • Pseudocode • Iteration • Recursion


• Top-down Approach • Bottom-up Approach • Illustrative

ss
Examples

re
1.1  INTRODUCTION
yP
sit
A program is a set of instructions that tells the computer how to solve a particular problem. Various program
design tools like algorithms, pseudocdes and flowcharts are used to design the blueprint of the solution
er

(or the program to be written). Computer programming goes a step further in problem solving process.
Programming means writing computer programs. While programming, the programmers take an algorithm
iv

and code the instructions in a particular programming language so that it can be executed by a computer.
Un

These days, there are many programming languages available in the market. The programmer can choose any
language depending on his expertise and the problem domain.
The following sections will deal with different program design tools, knowledge of which is compulsory
d

to develop programming skills.


or

1.2  ALGORITHMS
xf

In computing, we focus on the type of problems categorically known as algorithmic problems, where their
O

solutions are expressible in the form of algorithms. The term ‘algorithm’ was derived from the name of
Mohammed al-Khwarizmi, a Persian mathematician in the nineth century (Al-Khwarizmi → Algorism
(in Latin) → Algorithm). The typical meaning of an algorithm is a formally defined procedure for performing
some calculation. If a procedure is formally defined, then it must be implemented using some formal language,
and such languages are known as programming languages. The algorithm gives the logic of the program, that
is, a step-by-step description of how to arrive at a solution.
In general terms, an algorithm provides a blueprint to writing a program to solve a particular problem. It
is considered to be an effective procedure for solving a problem in a finite number of steps. That is, a well-
defined algorithm always provides an answer, and is guaranteed to terminate.
Algorithms are mainly used to achieve software reuse. Once we have an idea or a blueprint of a solution,
we can implement it in any language, such as C, C++, Java, and so on. In order to qualify as an algorithm, a
sequence of instructions must possess the following characteristics:
• Precision: The instructions should be written in a precise manner.
• Uniqueness: The outputs of each step should be unambiguous, i.e., they should be unique and only depend
on the input and the output of the preceding steps.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 1 14/06/18 7:49 PM


2 Problem Solving and Programming with Python

• Finiteness: Not even a single instruction must be repeated infinitely.


• Effectiveness: The algorithm should designed in such a way that it should be the most effective among
many different ways to solve a problem.
• Input: The algorithm must receive an input.
• Output: After the algorithm gets terminated, the desired result must be obtained.
• Generality: The algorithm can be applied to various set of inputs.

1.3  BUILDING BLOCKS OF ALGORITHM (INSTRUCTIONS, STATE,


CONTROL FLOW, FUNCTIONS)
An algorithm starts from an initial state with some input. The instructions/statements describe the processing
that must be done on the input to produce the final output (the final state). Note that an instruction is a single
operation which when executed converts one state to other.
In the course of processing, data is read from an input device, stored in computer’s memory for further

ss
processing, and then the result of the processing is written to an output device.

re
The data is stored in the computer’s memory in the form of variables or constants. The state of an algorithm
is defined as its condition regarding current values or contents of the stored data.

yP
An algorithm is a list of precise steps and the order of steps determines the functioning of the algorithm.
The flow of control (or the control flow) of an algorithm can be specified as top-down or bottom-up
sit
approach. Thus, the flow of control specifies the order in which individual instructions of an algorithm are
executed.
er

1.3.1  Different Approaches of Designing an Algorithm


iv

Algorithms are used to manipulate the data for a given problem. For a complex problem, its algorithm is
Un

often divided into smaller units called functions (or modules). This process of dividing an algorithm into
modules/functions is called modularization. The key advantages of functions (or modularization) are as
follows:
d

• It makes the complex algorithm simpler to design and implement.


or

• Each function can be designed independently. While designing one function, the details of other functions
can be ignored, thereby enhancing clarity in design which in turn simplifies implementation, debugging,
xf

testing, documenting, and maintenance of the overall algorithm.


O

There are two main approaches to design an algorithm—top-down approach and bottom-up approach, as
shown in Figure 1.1.

Top-down Complex algorithm Bottom-up


approach approach

Function 1 Function 2 Function n

Each function can be divided into one or more sub-functions


Figure 1.1  Different approaches of designing an algorithm

Top-down approach  A top-down design approach starts by dividing the complex algorithm into one or
more functions. These functions can further be decomposed into one or more sub-functions, and this process
of decomposition is iterated until the desired level of module complexity is achieved. Top-down design

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 2 14/06/18 7:49 PM


Algorithmic Problem Solving 3

method is a form of stepwise refinement where we begin with the topmost module and incrementally add
functions that it calls.
Therefore, in a top-down approach, we start from an abstract design and then at each step, this design is
refined into more concrete levels until a level is reached that requires no further refinement.
Bottom-up approach  A bottom-up approach is just the reverse of top-down approach. In the bottom-up
design, we start with designing the most basic or concrete functions and then proceed towards designing
higher level functions. The higher level functions are implemented by using the operations performed by
lower level functions. Thus, in this approach sub-functions are grouped together to form a higher level
function. All the higher level functions are clubbed together to form even higher level functions. This process
is repeated until the design of the complete algorithm is obtained.
Top-down vs bottom-up approach  Whether the top-down strategy should be followed or a bottom-up
is a question that can be answered depending on the application at hand. While top-down approach follows a
stepwise refinement by decomposing the algorithm into manageable function, the bottom-up approach on the

ss
other hand defines a function and then groups together several functions to form a new higher level function.
Top-down approach is highly appreciated for ease in documenting the functions, generation of test

re
cases, implementation of code, and debugging. However, it is also criticized because the sub-functions are

yP
analysed in isolation without concentrating on their communication with other functions or on reusability of
components and little attention is paid to data, thereby ignoring the concept of information hiding.
The bottom-up approach allows information hiding as it first identifies what has to be encapsulated within a
sit
function and then provides an abstract interface to define the function’s boundaries as seen from the clients. But all
this is difficult to be done in a strict bottom-up strategy. Some top-down activities need to be performed for this.
er

All in all, design of complex algorithms must not be constrained to proceed according to a fixed pattern
iv

but should be a blend of top-down and bottom-up approaches.


Un

1.4  ALGORITHMIC PROBLEM SOLVING STEPS


As mentioned earlier, algorithms are solutions to problems. They are not solutions themselves. They just
list specific instructions that need to be performed for getting the solution. In computer science, emphasis
d

is laid on writing a good and effective algorithm and this emphasis makes computer science distinct from
or

other disciplines. For example, computer science is distinct from theoretical mathematics because those
practitioners are typically satisfied with just proving the existence of a solution to a problem but in computer
xf

science, the problem is not solved until the algorithm is used to implement the solution.
O

We will now discuss about the sequence of steps one must typically follow for designing an effective algorithm.
1. Understanding the problem
2. Determining the capabilities of the computational device
3. Exact/approximate solution
4. Select the appropriate data structure
5. Algorithm design techniques
6. Methods of specifying an algorithm
7. Proving an algorithms correctness
8. Analysing the performance of an algorithm
Understanding the problem The problem given should be clearly and completely understood. It is
compared with earlier problems that have already been solved to check if it is similar to them and a known
algorithm exists. If the algorithm is available, it is used otherwise a new one has to be developed.
Determining the capabilities of the computational device  After understanding the problem, the
capabilities of the computing device should be known. For this, the type of the architecture, speed and
memory availability of the device are noted.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 3 14/06/18 7:49 PM


4 Problem Solving and Programming with Python

Exact/approximate solution  The next step is to develop the algorithm. The algorithm must compute
correct output for all possible and legitimate inputs. This solution can be an exact solution or an approximate
solution. For example, you can only have an approximate solution in case of finding square root of number
or finding the solutions of nonlinear equations.
Select the appropriate data structure  A data type is a well-defined collection of data with a well-
defined set of operations on it. A data structure is basically a group of data elements that are put together
under one name, and which defines a particular way of storing and organizing data in a computer so that it
can be used efficiently. The elementary data structures are as follows.
• List: Allows fast access of data.
• Sets: Treats data as elements of a set. Allows application of operations such as intersection, union, and
equivalence.
• Dictionaries: Allows data to be stored as a key-value pair.

ss
Algorithm design techniques  Developing an algorithm is an art which may never be fully automated.
By mastering the design techniques, it will become easier for you to develop new and useful algorithms.

re
Examples of algorithm design techniques include dynamic programming.

yP
Methods of specifying an algorithm  An algorithm is just a sequence of steps or instructions that can
be used to implement a solution. After writing the algorithm, it is specified either using a natural language or
with the help of pseudocode and flowcharts. We will read about them in the next section.
sit
Proving algorithms correctness Writing an algorithm is not just enough. You need to prove that it
er
computes solutions for all the possible valid inputs. This process is often referred to as algorithm validation.
Algorithm validation ensures that the algorithm will work correctly irrespective of the programming language
iv

in which it will be implemented.


Un

Analysing the performance of algorithms When an algorithm is executed, it uses the computer’s


resources like the Central Processing Unit (CPU) to perform its operation and to hold the program and data
respectively. An algorithm is analysed to measure its performance in terms of CPU time and memory space
d

required to execute that algorithm. This is a challenging task and is often used to compare different algorithms
or

for a particular problem. The result of the comparison helps us to choose the best solution from all possible
solutions. Analysis of the algorithm also helps us to determine whether the algorithm will be able to meet any
xf

efficiency constraint that exits or not.


O

1.5  SIMPLE STRATEGIES AND NOTATIONS FOR


DEVELOPING ALGORITHMS
An algorithm is a step–by–step procedure for solving a task or problem. However, these steps must be
ordered, unambiguous and finite in number. Basically, an algorithm is nothing but English-like representation
of logic which is used to solve the problem.
For accomplishing a particular task, different algorithms can be written. The different algorithms differ in
their requirements of CPU time and memory space. The programmer selects the best suited algorithm for the
given task to be solved.
Various strategies and notations used for developing and designing algorithms are discussed in the
following sections.

1.5.1  Control Structures Used in Algorithms


An algorithm has a finite number of steps and some steps may involve decision making and repetition. Broadly
speaking, an algorithm may employ three control structures, namely, sequence, decision, and repetition.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 4 14/06/18 7:49 PM


Algorithmic Problem Solving 5

Sequence  Sequence means that each step of the algorithm is executed in the specified order. An algorithm
to add two numbers is given as follows. This algorithm performs the steps in a purely sequential order.

Example 1.1 Algorithm to add two numbers

Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : Set Sum = A + B
Step 5 : Print Sum
Step 6 : End

ss
Decision  Decision statements are used when the outcome of the process depends on some condition. For
example, if x = y, then print “EQUAL”. Hence, the general form of the if construct can be given as follows:

re
IF condition then process

yP
A condition in this context is any statement that may evaluate either to a true value or a false value. In the
preceding example, the variable x can either be equal or not equal to y. However, it cannot be both true and
sit
false. If the condition is true then the process is executed.
A decision statement can also be stated in the following manner:
er

IF condition
iv

  then process1
Un

ELSE process2

This form is commonly known as the if-else construct. Here, if the condition is true then process1 is
d

executed, else process2 is executed. An algorithm to check the equality of two numbers is shown below.
or

Example 1.2 Algorithm to test the quality of two numbers


xf
O

Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : IF A = B
  Print "Equal"
ELSE
  Print "Not equal" [END of IF]
Step 5 : End

Let us look at the following two simple algorithms to find the greatest among three numbers.

Example 1.3 Algorithm to find the greatest of three numbers

Step 1: Start
Step 2: Read the three numbers A,B,C

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 5 14/06/18 7:49 PM


6 Problem Solving and Programming with Python

Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.


Step 4: C
ompare A and C. If A is greater, output "A is greatest" else output "C is
greatest"
Step 5: C
ompare B and C. If B is greater, output "B is greatest" else output "C is
greatest"
Step 6: End

Example 1.4 Algorithm to find the greatest of three numbers using an additional variable MAX

Step 1:
Start
Step 2:
Read the three numbers A,B,C

ss
Step 3:
Compare A and B. If A is greater, store Ain MAX, else store B in MAX
Step 4:
C
ompare MAX and C. If MAX is greater, output "MAX is greater" else output

re
"C is greater"
Step 5: End

yP
sit
Both the algorithms given in Examples 1.3 and 1.4 accomplish same goal, but in different ways. The
programmer selects the algorithm based on the advantages and disadvantages of each algorithm. For example,
er
the first algorithm has more number of comparisons, whereas in the second algorithm an additional variable
MAX is used to do the comparison.
iv

Iteration or repetition which involves executing one or more steps for a number of times, can be
Un

implemented using constructs such as the while loops and for loops. These loops execute one or more steps
until some condition is true.
d

Example 1.5 Algorithm that prints the first 10 natural numbers


or
xf

Step 1: Start
Step 2: [initialize] Set I = 1, N = 10
O

Step 3: Repeat Steps 3 and 4 while I <= N


Step 4: Print I
Step 5: Set I = I + 1 [END OF LOOP]
Step 6: End

Example 1.6 Design an algorithm for adding the test scores given as: 26, 49, 98, 87, 62, 75.

Step 1: Start
Step 2: sum = 0
Step 3: Get a value
Step 4: sum = sum + value
Step 5: If next value is present, go to step 3. Otherwise, go to step 6
Step 6: Print the sum
Step 7: End

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 6 14/06/18 7:49 PM


Algorithmic Problem Solving 7

Examples 1.5 and 1.6 demonstrate the application of repetition and iteration logic in an algorithm.
Some more examples to depict the concept of control structures in algorithms are given as follows.

Example 1.7 Write an algorithm for interchanging/swapping two values.

Step 1: Start
Step 2: Input first number as A
Step 3: Input second number as B
Step 4: Set temp = A
Step 5: Set A = B
Step 6: Set B = temp
Step 7: Print A, B
Step 8: End

ss
re
Example 1.8 Write an algorithm to find the larger of two numbers.

yP
Step 1:
Start
Step 2:
Input first number as A
sit
Step 3:
Input second number as B
Step 4:
IF A > B
er

Print A
ELSE IF A < B
iv

Print B
Un

ELSE
Print "The numbers are equal"
[END OF IF]
d

Step 5: End
or
xf

Example 1.9 Write an algorithm to find whether a number is even or odd.


O

Step 1: Start
Step 2: Input number as A
Step 3: IF A % 2 = 0
Print "Even"
ELSE
Print "Odd"
[END OF IF]
Step 4: End

Example 1.10 Write an algorithm to print the grade obtained by a student using the following rules:

Marks Grade
Above 75 O
60-75 A

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 7 14/06/18 7:49 PM


8 Problem Solving and Programming with Python

Marks Grade
50-60 B
40-50 C
Less than 40 D

Step 1: Start
Step 2: Enter the marks obtained as M
Step 3: IF M > 75
Print "O"
Step 3: IF M >= 60 and M < 75
Print "A"

ss
Step 4: IF M >= 50 and M < 60
Print "B"

re
Step 5: IF M >= 40 and M < 50

yP
Print "C"
ELSE
Print "D"
sit
[END OF IF]
Step 6: End
er
iv

Example 1.11 Write an algorithm to find the sum of first N natural numbers.
Un

Step 1: Start
d

Step 2: Input N
or

Step 3: Set I = 1, sum = 0


Step 4: Repeat Steps 4 and 5 while I <= N
xf

Step 5: Set sum = sum + I


O

Step 6: Set I = I + 1
[END OF LOOP]
Step 7: Print sum
Step 8: End

Recursion  It is a technique of solving a problem by breaking it down into smaller and smaller sub-problems
until you get to a small enough problem that it can be easily solved. Usually, recursion involves a function
calling itself until a specified condition is met. Since a recursive function repeatedly calls itself, it makes use
of the system stack to temporarily store the return address and local variables of the calling function. Every
recursive solution has two major cases. They are:
• Base case, in which the problem is simple enough to be solved directly without making any further calls
to the same function.
• Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the function
calls itself but with sub-parts of the problem obtained in the first step. Third, the result is obtained by com-
bining the solutions of simpler sub-parts.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 8 14/06/18 7:49 PM


Algorithmic Problem Solving 9

Therefore, recursion is defining large and complex problems in terms of smaller and more easily solvable
problems. In recursive functions, a complex problem is defined in terms of simpler problems and the simplest
problem is given explicitly.
(For a detailed study on Recursion and Iteration, refer to Chapter 5)

Example 1.12 Write a recursive algorithm to find the factorial of a number.

Step 1: Start
Step 2: Input number as n
Step 3: Call factorial(n)
Step 4: End

ss
factorial(n)
Step 1: Set f = 1

re
Step 2: IF n==1 then return 1
  ELSE

yP
  Set f=n*factorial(n-1)
Step 3: Print f
sit
er

1.5.2  Flowcharts Start or End Input/Output


A flowchart is a graphical or symbolic symbol symbol
iv

representation of a process. It is basically used


Un

to design and document virtually complex Arrows Decision symbol


processes to help the viewers to visualize the
logic of the process, so that they can gain a better
d

understanding of the process and find flaws, Processing step Connector


or

bottlenecks, and other less obvious features


within it. Pre-defined Process (Subroutine)
xf

When designing a flowchart, each step in the


process is depicted by a different symbol and is Figure 1.2  Symbols used in a Flowchart
O

associated with a short description. The symbols


in the flowchart (refer Figure 1.2) are linked together with arrows to show the flow of logic in the process.
The symbols used in a flowchart include the following:
• Start and end symbols are also known as the terminal symbols and are represented as circles, ovals, or
rounded rectangles. Terminal symbols are always the first and the last symbols in a flowchart.
• Arrows depict the flow of control of the program. They illustrate the exact sequence in which the instructions
are executed.
• Generic processing step, also called as an activity, is represented using a rectangle. Activities include
instructions such as add a to b or save the result. Therefore, a processing symbol represents arithmetic and
data movement instructions. When more than one process has to be executed simultaneously, they can
be placed in the same processing box. However, their execution will be carried out in the order of their
appearance.
• Input/Output symbols are represented using a parallelogram and are used to get inputs from the users or
display the results to them.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 9 14/06/18 7:49 PM


10 Problem Solving and Programming with Python

• A conditional or decision symbol is represented using a diamond. It is basically used to depict a Yes/No
question or a True/False test. The two symbols coming out of it, one from the bottom point and the other
from the right point, corresponds to Yes or True, and No or False, respectively. The arrows should always
be labelled. A decision symbol in a flowchart can have more than two arrows, which indicates that a
complex decision is being taken.
• Labelled connectors are represented by an identifying label inside a circle and are used in complex or
multi-sheet diagrams to substitute for arrows. For each label, the ‘outflow’ connector must have one or
more ‘inflow’ connectors. A pair of identically labelled connectors is used to indicate a continued flow
when the use of lines becomes confusing.
• A pre-defined process symbol is a marker for another process step or series of process flow steps that are
formally defined elsewhere. This shape commonly depicts sub-processes (or subroutines in programming
flowcharts).

Significance of Flowcharts

ss
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be performed

re
to solve a problem. It is usually drawn in the early stages of formulating computer solutions. It facilitates
communication between programmers and users. Once a flowchart is drawn, programmers can make users

yP
understand the solution easily and clearly.
Flowcharts are very important in the programming of a problem as they help the programmers to
sit
understand the logic of complicated and lengthy problems. Once a flowchart is drawn, it becomes easy for the
programmers to write the program in any high-level language. Hence, the flowchart has become a necessity
er
for better documentation of complex programs.
A flowchart follows the top-down approach in solving problems. Some examples are given as follows.
iv
Un

Example 1.13 D
 raw a flowchart to calculate the Example 1.14 D
 raw a flowchart to add two
sum of the first 10 natural numbers. numbers.
d
or

START START
xf

Set I = 1 Read the values


O

Set SUM = 0 of A and B

Set SUM = SUM + 1


Set I = I + 1 Calculate SUM = A + B

NO
Is I = 10?
Print SUM
YES
Display SUM
STOP

STOP

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 10 14/06/18 7:49 PM


Algorithmic Problem Solving 11

Example 1.15 D
 raw a flowchart to Example 1.16 D
 raw a flowchart to determine the largest of
calculate the salary of three numbers.
a daily wager.
START
START

Read the
SALARY Input the values of
no_of_hrs, pay_per_hr, A, B, and C
and travel_allowance Print B

YES
Calculate SALARY=(no_of_hr x NO NO

ss
pay_per_hr) + travel_allowance Is A > B? Is B > C? Print C
YES

re
NO

yP
Print SALARY Is A > C? Print C

YES
sit
Print A
STOP
er

STOP
iv
Un

Advantages
• They are very good communication tools to explain the logic of a system to all concerned. They help to
analyse the problem in a more effective manner.
d

• They are also used for program documentation. They are even more helpful in the case of complex
or

programs.
• They act as a guide or blueprint for the programmers to code the solution in any programming language.
xf

They direct the programmers to go from the starting point of the program to the ending point without
O

missing any step in between. This results in error-free programs.


• They can be used to debug programs that have error(s). They help the programmers to easily detect, locate,
and remove mistakes in the program in a systematic manner.

Limitations
• Drawing flowcharts is a laborious and a time-consuming activity. Just imagine the effort required to draw
a flowchart of a program having 50,000 statements in it!
• Many a times, the flowchart of a complex program becomes complex and clumsy.
• At times, a little bit of alteration in the solution may require complete redrawing of the flowchart.
• The essentials of what is done may get lost in the technical details of how it is done.
• There are no well-defined standards that limit the details that must be incorporated into a flowchart.

1.5.3  Pseudocodes
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of a programming language. It facilitates designers to focus on the logic of the algorithm without
getting bogged down by the details of language syntax. An ideal pseudocode must be complete, describing
the entire logic of the algorithm, so that it can be translated straightaway into a programming language.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 11 14/06/18 7:49 PM


12 Problem Solving and Programming with Python

It is basically meant for human reading rather than machine reading, so it omits the details that are not
essential for humans. Such details include variable declarations, system-specific code, and subroutines.
Pseudocodes are an outline of a program that can easily be converted into programming statements. They
consist of short English phrases that explain specific tasks within a program’s algorithm. They should not
include keywords in any specific computer language.
The sole purpose of pseudocodes is to enhance human understandability of the solution. They are commonly
used in textbooks and scientific publications for documenting algorithms, and for sketching out the program
structure before the actual coding is done. This helps even non-programmers to understand the logic of the designed
solution. There are no standards defined for writing a pseudocode, because a pseudocode is not an executable
program. Flowcharts can be considered as graphical alternatives to pseudocodes, but require more space on paper.

Example 1.17 W
 rite a pseudocode for calculating the price of a product after adding the sales tax to
its original price.

ss
1. Start

re
2. Read the price of the product
3. Read the sales tax rate

yP
4. Calculate sales tax = price of the item x * sales tax rate
5. Calculate total price = price of the product + sales tax
sit
6. Print total price
7. End
er

Variables: price of the item, sales tax rate, sales tax, total price
iv
Un

Example 1.18 W
 rite a pseudocode to calculate the weekly wages of an employee. The pay depends
on wages per hour and the number of hours worked. Moreover, if the employee has
d

worked for more than 30 hours, then he or she gets twice the wages per hour, for every
or

extra hour that he or she has worked.


xf

1. Start
2. Read hours worked
O

3. Read wages per hour


4. Set overtime charges to 0
5. Set overtime hrs to 0
6. IF hours worked > 30 then
a. Calculate overtime hrs = hours worked - 30
b. Calculate overtime charges = overtime hrs * (2 * wages per hour)
c. Set hours worked = hours worked - overtime hrs
ENDIF
7. Calculate salary = (hours worked x wages per hour) + overtime charges
8. Display salary
9. End
Variables: hours worked, wages per hour, overtime charges, overtime hrs, salary

Example 1.19 W
 rite a pseudocode to read the marks of 10 students. If marks is greater than 50, the
student passes, else the student fails. Count the number of students passing and failing.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 12 14/06/18 7:49 PM


Algorithmic Problem Solving 13

1. Start
2. Set pass to 0
3. Set fail to 0
4. Set no of students to 1
5. WHILE no of students < 10
a. input the marks
b. IF marks >= 50 then
    Set pass = pass + 1
ELSE
    Set fail = fail + 1
ENDIF
ENDWHILE
6. Display pass
7. Display fail

ss
8. End
Variables: pass, fail, no of students, marks

re
yP
1.5.4  Programming Languages
A programming language is a language specifically designed to express computations that can be performed
sit
by a computer. Programming languages are used to create programs that control the behaviour of a system,
to express algorithms, or as a mode of human communication.
er

Usually, programming languages have a vocabulary of syntax and semantics for instructing a computer
to perform specific tasks. The term programming language refers to high-level languages such as BASIC
iv

(Beginners’ All-purpose Symbolic Instruction Code), C, C++, COBOL (Common Business Oriented Language),
Un

FORTRAN (Formula Translator), Python, Ada, and Pascal, to name a few. Each of these languages has a unique
set of keywords (words that it understands) and a special syntax for organizing program instructions.
Though high-level programming languages are easy for humans to read and understand, the computer can
d

understand only machine language, which consists of only numbers. Each type of central processing unit
or

(CPU) has its own unique machine language.


In between machine languages and high-level languages, there is another type of language known as
xf

assembly language. Assembly languages are similar to machine languages, but they are much easier to
program because they allow a programmer to substitute names for numbers.
O

However, irrespective of the language that a programmer uses, a program written using any programming
language has to be converted into machine language so that the computer can understand it. There are two
ways to do this: compile the program or interpret the program.
When planning a software solution, the software development team often faces a common question—
which programming language to use? Many programming languages are available today and each one has
its own strengths and weaknesses. Python can be used to write an efficient code, whereas a code in BASIC is
easy to write and understand; some languages are compiled, whereas others are interpreted; some languages
are well known to the programmers, whereas others are completely new. Selecting the perfect language for a
particular application at hand is a daunting task.
The selection of language for writing a program depends on the following factors:
• The type of computer hardware and software on which the program is to be executed.
• The type of program.
• The expertise and availability of the programmers.
• Features to write the application.
• The built-in features that support the development of software that are reliable and less prone to crash.
• Lower development and maintenance costs.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 13 14/06/18 7:49 PM


14 Problem Solving and Programming with Python

• Stability and capability to support even more than the expected simultaneous users.
• Elasticity of a language that implies the ease with which new features (or functions) can be added to the
existing program.
• Portability.
• Better speed of development that includes the time it takes to write a code, time taken to find a solution to
the problem at hand, time taken to find the bugs, availability of development tools, experience and skill of
the programmers, and testing regime.
For example, FORTRAN is a particularly good language for processing numerical data, but it does
not lend itself very well to organizing large programs. Pascal can be used for writing well-structured and
readable programs, but it is not as flexible as the C programming language. C++ goes one step ahead of C by
incorporating powerful object oriented features, but it is complex and difficult to learn. Python, however is a
good mix of the best features of all these languages.
1.6  ILLUSTRATIVE PROBLEMS

ss
In this section, we will look into some common problems in computer science and will specify its solution by
writing an algorithm and pseudocode, and drawing its corresponding flowchart. (Besides these, we will study

re
some more illustrative examples in Appendix A.)

yP
1.6.1  Find Minimum in a List
Consider the following requirement specification.
sit
You are given a list of numbers from which you are supposed to find the minimum value. An algorithm is
required for entering the numbers in the list and then calculate the minimum value. The count of numbers to
er
be entered in the list should also be asked from the user.
Before writing the algorithm, just visualize how it works. Take the first number in the list and call it
iv

minimum. Compare the minimum’s value with all other values in the list one by one. The moment you find
a smaller element than the minimum, call it the minimum. Figure 1.3 given below illustrates this concept.
Un

3 5 9 1 4 7 2 6
d

Let MIN = 3, Compare MIN with every element in the list one by one.
or

3 5 9 1 4 7 2 6
xf

MIN < 5, so no change


O

3 5 9 1 4 7 2 6
MIN < 9, so no change
3 5 9 1 4 7 2 6
MIN < 1, so set MIN = 1
3 5 9 1 4 7 2 6
MIN < 4, so no change
3 5 9 1 4 7 2 6
MIN < 7, so no change
3 5 9 1 4 7 2 6
MIN < 2, so no change
3 5 9 1 4 7 2 6
MIN < 6, so no change
Figure 1.3  Finding minimum value in a list

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 14 14/06/18 7:49 PM


Algorithmic Problem Solving 15

The step-wise approach for solving the problem of finding the minimum in a list is demonstrated through
Algorithm 1.1, Flowchart 1.1, and Pseudocode 1.1.

Algorithm 1.1

Step 1: Start
Step 2: READ the count of numbers as N
Step 3: SET I = 0
Step 4: READ the first element as MIN
Step 5: REPEAT Steps 6-8 WHILE I < N – 1
Step 6: READ the next number as NUM
Step 7: IF MIN < NUM
SET MIN = NUM

ss
Step 8: SET I = I + 1
Step 9: PRINT MIN

re
Step 10: End

yP
Flowchart 1.1 sit
Start
er

Read the count


iv

of numbers as N
Un

SET I = 0
d
or

Read the first


xf

element as MIN
O

NO
Is I < N - 1? Print MIN
YES

Read the next Stop


number as NUM

NO
Is MIN < NUM?

YES

SET MIN = NUM

SET I = I + 1

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 15 14/06/18 7:49 PM


16 Problem Solving and Programming with Python

Pseudocode 1.1

Read the count of numbers as N


Set I = 0
Read the first element as MIN
While I < N – 1
Read the next number as NUM
IF MIN < NUM
Set MIN = NUM
Set I = I + 1
Print MIN
End
Variables: I, N, NUM, MIN

ss
1.6.2  Insert a Card in a List of Sorted Cards

re
Inserting a card in a list of sorted cards is same as inserting an element into a sorted list of numbers. For this,

yP
start from the end of the list and compare the new element with the elements of the list to find a suitable
position at which the new element has to be inserted. While comparing, also shift the elements one step ahead
to create a vacancy for the new element. Figure 1.4 given below illustrates this concept.
sit
Position 0 1 2 3 4 5 Element To Be Inserted
er

Original List 4 6 9 10 11 7
iv

7>11 × 4 6 9 10 11
Un

7>10 × 4 6 9 10 11
7>9 × 4 6 9 10 11
d

7>6  √ 4 6 7 9 10 11
or

Figure 1.4  Inserting a number in a sorted list


xf

The step-wise approach for solving the problem of inserting a card in a list of sorted cards is represented
through Algorithm 1.2, Flowchart 1.2, and Pseudocode 1.2.
O

Algorithm 1.2

Step 1: Start
Step 2: READ Number of elements in the sorted list as N
Step 3: SET I=0
Step 4: REPEAT Steps 5 and 6 WHILE I < N
Step 5: READ the Sorted list element as List[I]
Step 6: SET I = I + 1
Step 7: READ Element to be inserted as X
Step 8: SET I = N-1
Step 9: REPEAT Step 10 and 11 WHILE I >= 0 AND X<List[I]
Step 10: List[I+1] = List[I]
Step 11: SET I = I - 1
Step 12: List[I+1] = X
Step 13: End

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 16 14/06/18 7:49 PM


Algorithmic Problem Solving 17

Flowchart 1.2

Start

Read Number of
elements in the
sorted list as

SET I = 0

ss
NO Read Element to
Is I < N?
be insert as X

re
YES

yP
SET I = I + 1 Read the sorted list SET I = N - 1
element as List[I]
sit
er
Is I > 0 AND NO
SET List[I] = X
X<List[I]?
iv
Un

Stop
SET List[I+1] = List[I]
d

SET I = I - 1
or
xf
O

Pseudocode 1.2

Start
Read Number of elements in the sorted list as N
Set I=0
WHILE I < N
Read the Sorted list element as List[I]
Set I = I + 1
Read element to be inserted as X
Set I = N-1
WHILE I >= 0 AND X<List[I]
List[I+1] = List[I]
Set I = I - 1
List[I+1] = X
End

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 17 14/06/18 7:49 PM


18 Problem Solving and Programming with Python

1.6.3  Guess an Integer Number in a Range


Let us play a game. While playing this game you will be able to appreciate how two different solutions to the
same problem can vary so much in terms of efficiency. The game is that the computer will randomly select
an integer from 1 to N and ask you to guess it. To help you guess the number correctly, the computer will tell
you if each guess is too high or too low. The good thing is that there is no limit on number of guesses. You
can make as many guess as you want to guess that number.
There are two ways to succeed in this game. First is the linear search and second is the binary search. In
linear search, you will guess the number as 1, then 2, then 3, then 4, and so on, until you guessed the right
number. So you are guessing all the numbers as if they were lined up in a row. This technique is fine but just
wonder how many guesses you would have to make. If the computer selects N, you would need N guesses. If
N is 1 then, of course, you will make it in the very first guess itself. Even if N is a small number like 5 or 10,
then it is still fine but just imagine what will be the number of guesses if N is a large number.
Now let us explore the binary search technique. Since the computer tells you whether a guess is too low,

ss
too high, or correct, it is better to start by guessing N/2. If the number selected by the computer is less than
N/2, then using the computer’s information that the guess is too high, you can eliminate all the numbers from

re
N/2 to N in just one go. If the number selected by the computer is greater than N/2, then all elements from

yP
1 through N/2 are eliminated right away. So with one guess you have narrowed down your possible guesses
by half. Isn’t that interesting and an intelligent move? Keep on cutting down the set of possible numbers by
half with every guess that you make.
sit
While linear search technique required N guesses to win the game, binary search technique, on the other
hand, can make you win (or find the number) in at most log2N+1 guesses. The following table shows the
er

maximum number of guesses for linear search and binary search for a few number sizes:
iv

VALUE OF N Max Linear Search Guesses Max Binary Search Guesses


Un

10 10 4
100 100 7
d

1,000 1,000 10
or

10,000 10,000 14
xf

100,000 100,000 17
1,000,000 1,000,000 20
O

The step-wise approach for solving the problem of guessing an integer number in a given range is
demonstrated through Algorithm 1.3, Flowchart 1.3, and Pseudocode 1.3.

Algorithm 1.3

Step 1: Start
Step 2: SET I = 0
Step 3: READ the range of numbers as N
Step 4: SET NUM as a randomly selected number from 1 to N
Step 5: READ VAL as a value guessed by the user
Step 6: SET I = I + 1
Step 7: IF VAL = NUM
THEN PRINT "YOU WIN... You guessed the number in Ith Turn"
Go to Step 10

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 18 14/06/18 7:49 PM


Algorithmic Problem Solving 19

Step 8: IF VAL > NUM


THEN PRINT "VALUE TOO HIGH… PLAY AGAIN…."
Go to Step 5
Step 9: IF VAL < NUM
THEN PRINT "VALUE TOO LOW… PLAY AGAIN…."
Go to Step 5
Step 10: End

Flowchart 1.3

ss
re
Start

yP
SET I = 0
sit
Read the range
er

of numbers as N
iv
Un

SET NUM as a randomly


selected number from 1 to N
d

Read VAL as a value


or

guessed by the user


xf

SET I = 1 +1
O

PRINT "YOU WIN you


Is VAL = NUM? Stop
guessed the number
in Ith Turn"

PRINT "VALUE
TOO LOW... Is VAL > NUM?
PLAY AGAIN...."

PRINT "VALUE
TOO HIGH...
PLAY AGAIN...."

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 19 14/06/18 7:49 PM


20 Problem Solving and Programming with Python

Pseudocode 1.3

Start
Set I = 0
Read the range of numbers as N
Set NUM as a randomly selected number from 1 to N
Read VAL as a value guessed by the user
Set I = I + 1
While VAL != NUM
IF VAL = NUM
THEN PRINT "YOU WIN... You guessed the number in Ith Turn"
Exit
ELSEIF VAL > NUM

ss
THEN PRINT "VALUE TOO HIGH… PLAY AGAIN…."
ELSE

re
THEN PRINT "VALUE TOO LOW… PLAY AGAIN…."
End

yP
sit
1.6.4  Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion. It says, ‘if you can solve n–1 cases, then you
er

can easily solve the nth case’.


iv

We will discuss the tower of Hanoi problem using one, then two, and finally three rings. Figures 1.5(a) and
(b) explain the working of the tower of Hanoi problem using one and two rings.
Un
d
or

A B C A B C A B C
(Step 1) (Step 1) (Step 2)
xf
O

A B C A B C A B C
(Step 2) (Step 3) (Step 4)
(If there is only one ring, (If there is two rings, then first move ring 1 to the spare
then simply move the ring pole and then move ring 2 from source to the destination.
from source to the destination.) Finally move ring 1 from spare to the destination.)
(a) (b)
Figure 1.5  Working of tower of Hanoi problem using one and two rings

Now, consider at Figure 1.6 which shows three rings mounted on pole A. The problem is to move all these
rings from pole A to pole C while maintaining the same order. The main issue is that the smaller disk must
always come above the larger disk.

Rules of this problem include


• Only one disk can be moved among the towers at any given time.
• Only the “top” disk can be removed.
• No large disk can sit over a small disk.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 20 14/06/18 7:49 PM


Algorithmic Problem Solving 21

3 Disks
(1)

A B C A B C
(2) (3) (4)

A B C A B C A B C
(5) (6) (7)

A B C A B C A B C
Figure 1.6  Solving the Tower of Hanoi problem

ss
We will be solving this using a spare pole. In our case, A is the source pole, C is the destination pole, and B

re
is the spare pole. To transfer all the three rings from A to C, we will first shift the upper two rings (n–1 rings)
from the source pole to the spare pole (refer to Steps 1, 2 and 3 of Figure 1.6). Now that n–1 rings have been

yP
removed from pole A, the nth ring can be easily moved from the source pole (A) to the destination pole (C)
(refer to Step 4 of Figure 1.6). The final step is to move the n–1 rings from the spare pole (B) as well as pole
sit
(A) to the destination pole (C) (refer to Steps 5, 6, and 7 of Figure 1.6).
To summarize, the solution to our problem of moving n rings from A to C using B as spare can be given as:
er

Base case: If n=1


Move the ring from A to C using B as spare
iv

Recursive case:
Un

Move n – 1 rings from A to B using C as spare


Move the one ring left on A to C using B as spare
We can conclude that the steps to solve the tower of Hanoi problems are:
d

Step 1 − Move n-1 disks from source to the spare pole


or

Step 2 − Move nth disk from source to destination pole


xf

Step 3 − Move n-1 disks from the spare pole to the destination pole
The step-wise approach for solving the problem of tower of Hanoi is demonstrated through Algorithm 1.4,
O

Flowchart 1.4, and Pseudcode 1.4.

Algorithm 1.4 Hanoi(disk, source, dest, spare)

Step 1: Begin
Step 2: IF disk = 1
THEN Go to step 3
ELSE
Go to step 4
Step 3: Move disk from source to dest and then Go to Step 7
Step 4: CALL Hanoi(disk-1, source, spare, dest)
Step 5: Move disk from source to dest
Step 6: CALL Hanoi(disk-1, spare, dest, source)
Step 7: End

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 21 14/06/18 7:49 PM


22 Problem Solving and Programming with Python

Flowchart 1.4

Begin Hanoi (disk,source,dest,spare)

Is disk==1?
Hanoi (disk-1, source, Move disk from
spare, dest) source to dest

Hanoi (disk-1,
spare, dest, source)

ss
re
End Hanoi

yP
Pseudocode 1.4 sit
Begin Procedure Hanoi(disk, source, dest, spare)
IF disk = 1
er

THEN Move disk from source to dest


iv

ELSE
CALL Hanoi(disk -1, source, spare, dest)
Un

Move disk from source to dest


CALL Hanoi(disk -1, spare, dest, source)
End Procedure Hanoi(disk, source, dest, spare)
d
or

Note: Refer to Program 5.17 for the code demonstrating the implementation of the solution of the
xf

tower of Hanoi problem.


O

Types of Errors
While writing programs, very often we get errors Types of errors
in our programs. These errors if not removed will
either give erroneous output or will not let the
compiler to compile the program. These errors
are broadly classified under four groups as shown Run-time Syntax Linker Logical
in Figure 1.7. errors errors errors errors
Run-time Errors  As the name suggests, run-
Figure 1.7  Types of errors
time errors occur when the program is being run
executed. Such errors occur when the program performs some illegal operations like
• dividing a number by zero
• opening a file that already exists
• lack of free memory space
• finding square or logarithm of negative numbers

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 22 14/06/18 7:49 PM


Algorithmic Problem Solving 23

Run-time errors may terminate program execution, so the code must be written in such a way that it handles
all sorts of unexpected errors rather terminating it unexpectedly.
Syntax Errors  Syntax errors (also known as compile-time errors) are generated when rules of a programming
language are violated. Python interprets (executes) each instruction in the program line by line. The moment the
interpreter encounters a syntactic error, it stops further execution of the program.
Semantic or Logical Errors  Semantic errors are those errors which may comply with rules of the programming
language but gives an unexpected and undesirable output which is obviously not correct. For example, if you write a
program to add two numbers but instead of writing ‘+’ symbol, you put the ‘–’ symbol.Then Python will subtract
the numbers and returns the result. But, actually the output is different from what you expected.
Logical errors are errors in the program code. Such errors are not detected by the compiler, and programmers
must check their code line by line or use a debugger to locate and rectify the errors. Logical errors occur due to
incorrect statements.
Linker Errors These errors occur when the linker is not able to find the function definition for a given prototype.

ss
re
yP
Summary
• Programming means writing computer programs. While • An algorithm is analysed to measure its performance in
sit
programming, the programmers takes an algorithm and terms of CPU time and memory space required to exe-
code the instructions in a particular programming lan- cute that algorithm
er

guage, so that it can be executed by a computer. • Sequence means that each step of the algorithm is exe-
• An algorithm provides a blueprint to writing a program cuted in the specified order.
iv

to solve a particular problem. • Decision statements are used when the outcome of the
Un

• In the course of processing, data is read from an input process depends on some condition.
device, stored in computer’s memory for further pro- • Iteration or Repetition involves executing one or more
cessing and then the result of the processing is written steps for a number of times, can be implemented using
d

to an output device. constructs such as the while loops and for loops.
or

• The data is stored in the computer’s memory in the form • Programming languages have a vocabulary of syntax
of variables or constants. and semantics for instructing a computer to perform
xf

• The flow of control (or the control flow) of an algorithm specific tasks.
can be specified as top-down or bottom-up approach. • Pseudocode facilitates designers to focus on the logic
O

• For a complex problem, its algorithm is often divided of the algorithm without getting bogged down by the
into smaller units called functions (or modules). details of language syntax.
• Algorithm validation ensures that the algorithm will
work correctly irrespective of the programming lan-
guage in which it will be implemented.

Glossary
Program  A set of instructions that tells the computer how Top-down design approach  Algorithm design approach
to solve a particular problem. that starts by dividing the complex algorithm into one or
Algorithm  A step by step instructions that tells the more functions.
computer how to solve a particular problem. Bottom-up design In this approach, we start with
Programming  The act of writing programs. designing the most basic or concrete functions and then
Instruction  A single operation which when executed proceed towards designing higher level functions.
convert one state to other. Programming language  A language specifically
Modularization  The process of dividing an algorithm designed to express computations that can be performed
into modules/functions. by a computer.

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 23 14/06/18 7:49 PM


24 Problem Solving and Programming with Python

Pseudocode  A compact and informal high-level Recursion  A technique of solving a problem by


description of an algorithm that uses the structural breaking it down into smaller and smaller sub-problems
conventions of a programming language. until you get to a small enough problem that it can be
Flowchart  A diagrammatic representation that illustrates the easily solved.
sequence of steps that must be performed to solve a problem.

Exercises
Fill in the blanks
1. A ________is a set of instructions that tells the 9. The ______ symbol is always the first and the last
computer how to solve a particular problem. symbol in a flowchart.
2. Algorithms are mainly used to achieve _________. 10. ______ is a form of structured English that describes

ss
3. _____ and _______ statements are used to change algorithms.
the sequence of execution of instructions. 11. ______ is used to express algorithms and as a mode

re
4. ______ is a formally defined procedure for of human communication.
performing some calculation. 12. The process of dividing an algorithm into modules/

yP
5. ______ statements are used when the outcome of the functions is called _________.
process depends on some condition. 13. In a _________ approach, we start from an abstract
sit
6. Repetition can be implemented using constructs such design and then at each step, this design is refined
as ______, ______, and ______. into more concrete levels until a level is reached that
7. A complex algorithm is often divided into smaller requires no further refinement.
er

units called ______. 14. _________is a technique of solving a problem by


iv

8. _____ design approach starts by dividing the complex breaking it down into smaller and smaller sub-
algorithm into one or more modules. problems until you get to a small enough problem
Un

that it can be easily solved.

State True or False


d
or

1. An algorithm solves a problem in a finite number of 6. Terminal symbol depicts the flow of control of the
steps. program.
xf

2. Flowcharts are drawn in the early stages of 7. Labelled connectors are square in shape.
formulating computer solutions. 8. The outputs of each step of an algorithm should be
O

3. The main focus of pseudocodes is on the details of unambiguous. This means that is should be precise.
the language syntax. 9. You can have maximum one function in a algorithm.
4. Algorithms are implemented using a programming 10. A top-down design approach starts by dividing the
language. complex algorithm into one or more functions.
5. Repetition means that each step of the algorithm is 11. Pseudocode is written using the syntax of a particular
executed in a specified order. programming language.

Multiple Choice Questions


1. Algorithms should be 3. Which one of the following is a graphical or symbolic
(a) precise (b) unambiguous representation of a process?
(c) clear (d) all of these (a) algorithm (b) flowchart
2. To check whether a given number is even or odd, you (c) pseudocode (d) program
will use which type of control structure? 4. In a flowchart, which symbol is represented using a
(a) sequence (b) decision rectangle?
(c) repetition (d) all of these (a) terminal (b) decision
(c) activity (d) input/output

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 24 14/06/18 7:49 PM


Algorithmic Problem Solving 25

5. Which of the following details are omitted in (b) measure the memory consumed
pseudocodes? (c) check if it is correct
(a) variable declaration (d) all of these
(b) system specific code 8. Programming languages have a vocabulary of
(c) subroutines ___________ for instructing a computer to perform
(d) all of these specific tasks.
6. A single operation which when executed convert one (a) syntax (b) semantics
state to other is called _________. (c) both of these (d) none of these
(a) instruction (b) program 9. Syntax and semantics of a language are strictly
(c) software (d) control checked in ___________.
7. Algorithm is validated to (a) algorithm (b) flowchart
(a) measure its CPU time (c) pseudocode (d) program

Review Questions

ss
1. Define an algorithm. How is it useful in the context 11. Write an algorithm and draw a flowchart that
of software development? calculates salary of an employee. Prompt the user

re
2. Explain and compare the approaches for designing to enter the Basic Salary, HRA, TA, and DA. Add

yP
an algorithm. these components to calculate the Gross Salary. Also
3. What is modularization? deduct 10% salary from the Gross Salary to be paid
4. Explain sequence, repetition, and decision as tax.
sit
statements. Also give the keywords used in each type 12. Draw a flowchart and write an algorithm and a
of statement. psuedocode for the following problem statements
er
5. With the help of an example, explain the use of a (a) Cook maggi
flowchart. (b) Cross road
iv

6. How is a flowchart different from an algorithm? (c) Calculate bill of items purchased
Do we need to have both of them for program (d) To find out whether a number is positive or
Un

development? negative
7. What do you understand by the term pseudocode? (e) Print “Hello” five times on the screen
8. Differentiate between algorithm and pseudocodes. (f) Find area of a rectangle
d

9. Give the characteristics of an algorithm. (g) Convert meters into centimeters


or

10. What do you understand by the term recursion? (h) Find the sum of first 10 numbers
xf
O

Answers
Fill in the Blanks
1. Program 5. Decision  8. top-down 12.  Modularization
2.  software reuse 6. while, do-while, and for   9.  Terminal symbols 13. top-down
3.  Decision, repetition loops 10. Psuedocode 14. Recursion
4. Algorithm 7.  functions or modules 11. Flowcharts

State True or False


 1. True  2. True  3. True  4. False  5. False  6. False  7. False  8. False  9. False
10. True  11. False

Multiple Choice Questions


1. (d)  2. (b)  3. (b)  4. (c)  5. (d)  6. (a)  7. (c)  8. (c)  9. (d)

© Oxford University Press. All rights reserved.

Problem Solving and Programming with Python.indb 25 14/06/18 7:49 PM

You might also like