You are on page 1of 15

2Brief Contents

Preface
Brief Contents x
Road Map to Syllabus xv

1. Algorithmic Problem Solving


itaube
Annexure 1-Introduction to Object Oriented Programming (OOP) 25

2. Basics of Python Programming


irogtto e001d pnibiod 37
Annexure 2-Installing Python 83
Annexure 3-Comparison berween Python 2.x and Python 3.x Versions 85
88
Annexure 4-Testing and Debugging
95
3. Control Flow Statements Ssioehbe 140
Case Stuc)y 1-Simple Calculator Funto
143
Case Studhy 2-Generating a Calendar ok a t o a k b
145
4. Functions
Annexure 5-Functions as Objects 187
Case Study 3-Shufiing a Deck of Cards 189
190
5. Strings
6. Lists, Tuples, and Dictionaries 233
0 303
7. File Handling
Case Study 4-Creating a Hash File (or a message digest of afile) a 334
336
Case Study 5-Mail Merge Program
338
Case Study 6-Finding Resolution of an Image
8. Error and Exception Handling, Modules, and Packages 339
Annexure6-Classes and Objects 369
w 381
Case Study 7-Compressing Sring and riues
Appendix A-Lab Exercises 384
Appendix B-GUIProgramming with tkinter Package 407
417
Appendix C-Simple Graphics using Turtle 423
AppendixD-Plotting Graphs in Python
Solved Question Paper (2018/19) e LC 429
Solved Question Paper (2017/18) h t kc 444
Solved Model Question Paper- 461
Solved Model Question Paper - 2 463
About the Author 465
Algorithmic
CHAPTER

1 Problem Solving
(2MOTVU3WOR JORTMOD

KEK Algorithm Flowchart Pseudocode Iteration Recursion


Illustrative Examples

Corcepts
anietocodapaiore go toubo.ar bggle seioogto eif a an
20 baniovgasd neo cotiogle ns 1o (wof loto09edhmo lonuosto dt
1.1 INTRODUCTION lsubviboi daidur gt Tobto sdi 201o0g loinoo
Aprogram is a set of instructions that tells the computer how to solve a particular problem. Various program
design tools like algorithms, pseudocdes and fowcharts are used to design the blueprint of the solution
(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
and code the instructions in a particular programming language so that it can be executed by a computer
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
to develop programming skills.

1.2 ALGORITHMS
In computing, we focus on the type of problems categorically known as algorithmic problems, where their
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 performing8
some calculation. Ifa 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, CH, 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.
Finiteness: Not even a single instruction
must be repeated infinitely.
2 Problem Solving and Programming with Python

should designed in such a way that it should


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

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. for further
in computer's memory
In the course of processing, data is read from an input device, stored
device.
processing, and then the result of the processing is written to output
an
The data is stored in the computer's memory in the form of variables or constants. The state of an algorithmn
is defined as its condition regarding current values or contents of the stored data.
An algorithm is a list of precise steps and the order of steps determines the functioning of the algorithm.
The fiow ofcontrol (or the control fow) of an algorithm can be specified as top-down or bottom-up approach.
Thus, the flow of control specifies the order in which individual instructions of an algorithm are executed

1.3.1 Subcharts/Subroutine/Predefined Processb


A subroutine (or procedure or function or routine) is a sequence of instructions that performs a specific
task. These instructions are packaged as a single unit and can be used (or invoked or called) wherever that
particular task needs to be performed. After performing its defined task, the sub-routine branches back (or
returns) to the next instruction after the one that invoked it. oTt.ersb aseil
A subroutine may be designed to accept one or more data values (also known as parameters) from the
calling code. It may also return a value to its caller. A subroutine can also be written in such a way that it
calls itself repeatedly. ob
The subroutine symbol is used to write steps for procedures. These procedures can be called from
anywhere in the code. This means that once the flowchart for a process is drawn, it can be referenced and
used from anywhere in the code,.
Rot ow iumoa nl

1.4 ALGORITHMIC PROBLEM SOLVING STEPS


As mentioned earlier, algorithms are solutions to'
e i e a betol
list specific instructions that need to be
problems. They are not solutions themselves. They Just
performed for getting the solution. In computer science,
1s laid on writing a good and effective algorithm and this emphasis makes computer science distinct from emphasis
oner 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 compute
science, the problem is not solved until the algorithm is used to implement the solution.
We will now discuss about the sequence of steps one must typically follow for designing an efective
algorithm.
1. Understanding the
problem
2. Determining the
capabilities of the computational device
3. Exact/approximate solution
irodrw ed bisode aeionat o:olaloeyt
4. Select the appropriate data structure UOUgdh d bi gpta da to eps ot eropin
5. Algorithm design
techniques
6. Methods of specifying an
algorithm
3
o fiegoimAlgorithmic Problem Solving

7. Proving an algorithms correctmess


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.
Exact/approximate solution The next step is to develop the algorithm. The algorithm must compute
corect 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 non-linear 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
data in a computerso that it
under one name, and which defines a particular way of storing and organizing
can be used The elementary data structures are as follows.
efficiently.
List: Allows fast access of data.
elements of a set. Allows application of operations such as intersection, union, and
Sets: Treats data as

equivalence.
Dictionaries: Allows data to be stored as a key-value pair.
is art which may neverbe fully automated.
Algorithm design techniques Developing algorithmfor
an an

it will become easier you to develop new and useful algorithms.


By mastering the design techniques,
Examples of algorithm design techniques
include dynamic programming.
of steps or instructions that can
Methods of specifying an algorithm An algorithm just sequence
is a
a natural language or
the algorithm, it is specified either using
be used to implement a solution. After writing
will read about them in the next section.
with the help of pseudocode and flowcharts. We
You need to prove that it
correctness Writing an algorithm is not just enough.
Proving algorithms is often referred to as algorithm validation.
solutions for all the possible valid inputs. This process
computes
will work correctly irrespective of the programming language
Algorithm validation ensures that the algorithm
in which it will be implemented.
When an algorithm is executed, it uses
the computer's resources
Analysing the performance of algorithms to hold the program and data respectively. An
Central Processing Unit (CPU) to perform its operation and
like the execute that
to measure its performance in terms
of CPU time and memory space required to
algorithm is analysed The
This is a challenging task and is often
used to compare different algorithms for a particular problem.
algorithm. solutions. Analysis of the algorithm
choose the best solution from all possible
result of the comparison helps us to exits or not.
determine whether the algorithm will be able to meet any eficiency constraint that
also helps us to

STRATEGIES AND NOTATIONS FOR


1.5 SIMPLE
DEVELOPING ALGORITHMS
must be
step-by-step
is procedure for solving a task or problem. However, these steps
An algorithm a
is nothing but English-like representation
ordered, unambiguous and finite in number. Basically, algorithm
an

of logic which is used to solve the problem.


can be written. The different algorithms
differ in
For accomplishing a particular task, different algorithms
selects the best suited algorithm for the
their requirements of CPU time and memory space. The programmer
given task to be solved.
Programming with Python
Problem Solving and Algorithmic Problem Solving

are discussed in the


strategies and notations used for developing and designing algorithms Let us look at the following two simple algorithms to find the greatest among three numbers.
Various
following sections.

w boeqo Example 1.3 Algorithm to find the greatest of three numbers


1.5.1 Control Structures Used in Algorithms
involve decision making and repetition. Broadly
has a finite number of steps and some steps may Step 1: Start
Analgorithm three control structures, namely, sequence,
decision, and repetition. Step 2: Read the three numbers A,B,C
speaking, an algorithm may employ is executed in the specified order. An algorithm Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.
Sequence means that each step of the algorithm
Sequence the steps n a purely sequential order, Step 4: Compare A and C. If A is greater, output "A is greatest" else output "C is
toadd two numbers is given as follows. This algorithm performs Breatest"

Step 5: Compare B and C. If B is greater, output "B is greatest" else autput "C is
add two numbers greatest"
Example 1.1 Algoithm to
Step 6: End

Step 1 : Start
gto eroie gteaiol
Input first number as A
n s boshgonge ed 1oeiod
Step
Step
2
3: Input second number as B
Example 1.4 Algorithm to find the greatest of three numbers using an additional variable MAX
Step 4 Set Sum= A +B
step 1: Start
Step 5 : Print Sum
Step 2: Read the three numbers A,B,C
Step 6 : End
Step 3: Compare A and B. If A is greater, store Ain MAX, else store B in MAX
Step 4: Compare MAX and C. If MAX is greater, output MAX i s greater else output
"C is greater"
Decision Decision statements are used when the outcome of the process depends on some condition. For Step 5: End
example, ifx =y, then print "EQUAL". Hence, the general form of the if construct can be given as followS
IF condition then process
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,
Acondition in this context is any statement that may evaluate either to a true value or a false value. In the
the first algorithm has more number of comparisons, whereas in the second algorithm an additional variable
preceding
false. If
example, the variable can either be equal or not equal to .
x However, it cannot be both true and
the condition is true then the process is executed. MAX is used to do the comparison.

Adecision statementcan also be statedinthefollowing manner:wotb elpeobuecg 3o gedpr diw Iteration or repetition which involves executing one or more steps for a number of times, can be
implemented using constructs such as the while loops and for loops. These loops execute one or more steps
IF condition eaerdopmea eprinouis.RYe until some condition is true.
then processi ble oldiazog sl lls 101 250i30loe zoltqeo2
ELSE process2
Example 1.5 Algorithm that prints the first 10 natural numbers
This form is commonly known as the if-else construct. Here, if the condition is true then
executed, else process2 is executed. An algorithm to check the equality of two numbers is shown processI is
Step 1: Start
below.
Step 2: [initialize] Set I = 1, N 10
Example 12 Algorithm to test the quality of two numbers Step 3: Repeat Steps 3 and 4 while I <= N
Step 4: Print I
Step 1 : Start Step 5: Set I = I + 1 [END OF LOOP]

Step 2
Input first number as A
: Step 6: End
Step 3: Lnputt
Step 4 IF A=B Second number as B

Print Equal 9HTRo238 DIgoJaVad Example 1.6 Design an algorithm for adding the test scores given as: 26, 49, 98, 87, 62, 75.
ELSE
Pránt Not equal"
[END of IF] Step 1: Start
Step 5:End
Step 2: sum 0
Step 3: Get a value
Problem Solving and
Programming
with Python
Algorithmic Problem Solving 7
Example 1.10 Write an algoríthm to prínt the grade obtained by a student using the following rules
8O t o step b
Step 4:
Sum sum+ value
is present, go
to step 3.
0therwise
Marks Grade
I f next value Above 75
Step 5:
P r i n t the sum
Step 6: 60-75
Step 7: End
algorithm. 50-60
and iterationlogic in an
demonstrate the application ofrepetition in algorithms
are given as
follows. -50
1.6
Examples 1.5 and
structures

to depict the concept of control Less than 40


Some more examples
two values.
interchanging/swapping

Write an algorithm for


Example1.7 Step 1: Start
Step 2: Enter the marks obtained as M
Step 1: Start
fhirst number as
A Step 3: IF M 75
Step 2: Input Print "O"
number as B
Step 3: Input second
Step 3: IF M >= 60 and M< 75
Set temp=A
Step 4: B
Print "A"
Step 5: Set A= Step 4: IF M = 50 and M < 60
Step 6: Set B -
temp
Print "B"
7: Print A, B
Step Step 5: IF M >= 40 and M<50
Step 8: End
Print "C"
ELSE
of two numbers. Print "D"
Write an algorithm to find the larger
Example 1.8 [END OF IFJ
Step 6: End
Step 1: Start
A
Step 2: Input first number as

second number as B
Step 3: Input
.
Step 4: IF A> B Example 1.11 Write an algorithm to find the sum of first N natural numbers.
Print A
ELSE IF A<B Step 1: Start
Print B Step 2: Input N
ELSE Step 3: Set I = 1, sum =
Print The numbers are equal Step 4: Repeat Steps 4 and 5 while I <= N
[END OF IF] Step 5: Set sum= sum+I
Step 5: End Step 6: Set I = I+1
[END OF LOOP]
Step 7: Print sum 0
Example 1.9 Write an algorithm to find whether a number is even or odd. Step 8: End

Step 1: Start
Step 2: Input number asA Recursion It is a technique of solving a problem by breaking it down into smaller and smaller sub-problems
Step 3: IF A % 2 until you get to a small enough problem that it can be easily solved. Usually, recursion involves a function
Print"Even" calling itself until a specified condition is met, Since a recursive function repeatedly calls itself, it makes use
ELSE of the system stack to temporarily store the return address and local variables ofthe calling function. Every
Print "Odd" recursive solution has two major cases. They are:
[END OF IF]
Step 4: End Base case, in which the problem is simple enough to be solved directly without making any further calls
to the same function.
Programming with Python
Problem Solving and er Algorithmic Problem Solving
into simpler sub-parts.
Second the function
first the problem at hand
is divided is obtained by com. npuiOutput symbols are represented using a parallelogram and are used to get inputs from the users or
in which Third, the result display the results to them.
Recursive case, obtained in the first step.
callsitself but with sub-parts of the problem A condifional
or decision
symbol is represented using a diamond. It is basically used to depict a Yes/No
the solutions of simpler sub-parts.
bining terms of
smaller and more easily solvable question True/False test. The two symbols coming out of it, one from the bottom
or a
problems in problems and the simplest
point and the other
Therefore, recursion is defining
large and complex from the right point, corresponds to Yes or True, and No or False, respectively. The arrows should always
is defined in terms ofsimpler
recursive functions, a complex problem be labelled. A decision
symbol in a flowchart can have more than two arrows, which indicates that a
problems. In
problem is given explicitly
complex decision is being taken.
Iteration, refer to Chapter
4)
and Labelled connectors are
(For a detailed stud on Recursion represented by ap identifying label inside a circle and are used in complex or
multi-sheet diagrams to substitute for arrows. For each label, the
factorial of a number. 'outfow connector must have one or
to find the more 'inflow' connectors. A
pair of identically labelled connectors is used to indicate a continued fow
Write a recursive algorithm
Example 1.12 when the use of lines becomes confusing.
Apre-definedprocess symbolisamarkerfor anotherprocessstep orseries
defined elsewhere. This
ofprocessfow stepsthatareformaly
Step 1: Start
Step 2: Input
number a s n
shape commonly depicts sub-proceses (or
subroustines in
programming flowcharts)
factorial (n) Significance of Flowcharts
Step 3: Call
A
Step 4: End flowchart is a diagrammatic representation that illustrates the sequence of steps that must be performed
to solve a problem. It is usually drawn in the early stages of formulating computer solutions. It facilitates
factorial (n) communication between programmers and users. Once a flowchart is drawn, programmers can make users
f= 1 understand the solution easily and clearly.
Step 1: Set
1
Step 2: IF ne-1 then return Flowcharts are very important in the programming of a problem as they help the programmers to
ELSE understand the logic of complicated and lengthy problems. Once a flowchart is drawn, it becomes easy for
Set fnfactorial (n-1) the
programmers to write the program in any high-level language. Hence, the flowchart has become a necessity
Step 3: Print f for better documentation of complex programs.
A flowchart follows the top-down approach in solving problems. Some examples are given as follows.

1.5.2 Flowcharts Start or End Input/Output Drawa fowchart add two


A fowchart 1s a graphical or
symbolic mb ol symbol Example1.13 Draw a flowchart to calculate the Example L.14 to

sum ofthe first 10 natural numbers. numbers.


representation of a process. It is basically used xolqinoo to e8 9
to design and document virtually complex Arrows Decision symbol
processes to help the viewers to visualize the START
START
logic ofthe process, so that they can gain a better Processing step Connector
understanding of the process and find fiaws,
Set I Read the values
bottlenecks, and other less obvious features of A and B
within it Pre-defined Process (Subroutine) Set sUM 0

When designing a flowchart, each step in the


Figure 1.1 Symbols used in a Flowchart
process is depicted by a different symbol and is Set sUM SUM + 1 Calculate SUM = A+ B
associated with a short description. The symbols Set I =I +1
in
the fowchat(refer Figure 1.1) are linked together with
The symbols used in flowchart include the following
a
arrows to show the flow of logic in the process.

NO
Start and end symbols are also known as the terminal symbols and are represented as circles, ovals, or Is I = 10? Print SUM
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 YES
are executed
Display SUM STOP
Generic processing step, also called activity, represented using a rectangle. Activities include
as an is
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 STOP
beplaced in the same processing box. However, their execution will be carried out in the order of their
appearance.
with Python
Problem Solving
and Programming
Algorithmic Problem Solving 11
10
1.16 Draw aflowehart to detemine thelargest of It is basically meant for human reading rather than machine reading, so it omits the details that are not
Draw a flowchart to
Example
Example
1.15 three numbers.
calculate the of
salary essential for humans. Such details include variable declarations, system-specifc code, and subroutines.
Pseudocodes are an outline of a program that can easily be converted into
a daily wager programming statements. 1 hey
START
consistofshort English phrases that explain specific tasks within a program's algorithm. They should not
include keywords in any specific computer language.
START
The sole purpose of pseudocodes is to enhance human understandability of the solution They are commonly
Read the
usedintextbooks and scientific publications for documenting algorithms, andfor sketching out the program
values of
SALARY Input the
ade-lar structure beforetheactual codingis done. This heipsevennon-programmerstounderstand thelogic ofthedesigned
A, B, and C solution.
no_of_hrs, paype Print B Thereare no standards
program. Flowcharts
defined for writing a pseudocode, because a pseudocode is not an executable
be considered graphical altematives to pseudocodes, but require more
and travel_allowance
can as
spaceon paper
YES
C a l c u l a t e SALARY=(no_of_hr x
ds A>B Bs
C Print c Example 1.17 its
Write apseudocodefor calculating the price of aproduct afteradding the salestax to
original price.
p a yper_hr)+ travel_allowance

YES 1. Start

Print SALARY ds A
C 0Print c 2. Read the price of the product
3. Read the sales tax rate
YES 4. Calculate sales tax = price of the item xsales tax rate
Print A 5. Calculate total price = price of the product + sales tax
STOP 6. Print total price
7. End
STOP
Variables: price of the item, sales tax rate, sales tax, total price
Advantages
They are very good communication tools to explain the logic of a
analyse the problem in a more effective manner.
system to all concerned. They help to Example 1.18 Write 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
hey are also used for program documentation. They are even more helpful in the case of complex
progralns. worked for more than 30 hours, then he or she gets twice the wages per hour, for every
They act as a guide or blueprint for the programmers to code the solution in any programming language wonD 99802 extra hour that he or she has worked.
1heydirect the programmers to go from the starting point of the program to the ending point without 1. Start
missing any step in between. This results in error-free programs. Read hours wOrked
They can be used to debug programs that have error(s). They help the programmers to 2
easily detect, locate, 3. Read wages per houn
and remove mistakes in the program in a
systematic manne 4. Set overtime charges to a
Limitations 5. Set Overtime hrs to 0
6. IF hours worked 30 then
Drawing fiowcharts is a laborious and a
of a program having 50,000 time-consuming activity. Just imagine the effort required to
a ffowchart
draw 3 a Calculate overtime hrs hours worked 30
Many a times, the fiowchart of a complexstatements in it! b Calculate overtime charges=overtime hrs (2 * wages per hour)

a program becomes complex and clumsy,


At times, little bit of alteration in the solution C. Set hours worked hours worked overtime hrs
The essentials of what is done may get lost in themay require complete redrawing of the flowchart ENDIF
technical
There are no
well-defined standards that limit the details thatdetails of how it is done.
must be
7. Calculate salary
8. Display salary
(hours worked x wages per hour)+overtime charges
1.5.3 Pseudocodes incorporated into a flowehart. 9. End
Pseudocode is a
compact and informal Variables : hours Worked, wages per hour, overtime charges, overtime hrs, salary
conventions of aprogramming language. Ithigh-level description of an
facilitates designers to focus onalgorithm that uses the structural
getting bogged down by the details of the
syntax. An ideal pseudocode logic
of the
the entire logic of the algorithm, so thatlanguage must be
algorithm without
it can be translated
straightaway into a
complete, describing Example 1.19 Write a pseudocode to read the marks of 10 students. If marks is greater than 50, the
programming language. student passes, else the student fails. Count the number of students passing and failing.
with Python
12 Problem SoMing and Programming eAlgorithmic Problem Solving 13

Elasticity of a language that implies the ease with which new features (or functions) can be added to the
1. Start existing program.
2. Set pass to Portability.
Set fail to e Better speed of development that includes the time it takes to write a code, time taken to find
4 Set no of
students to 1
the problem at hand, time taken to find the bugs, availability of development tools, a solution to
S. HILE no of students
1e
the programmers, and
testing regime. experience and skill of
a inpt the marks For example, FORTRAN is a
b. 1F marks se then particularly good language for processing numerical data, but it does
Set pasSpas +1 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
ELSE
programming
doorol incorporating powerful object oriented features, but it is complexlanguage. C goes one step ahead of C by
Set f a i l - f a i l + 1
and difficuit to leam.
ENDIF
good mix of the best features of all these languages. Python, however is a
ENDNHTLE
6. Display pass 1.6 ILLUSTRATIVE PROBLEMS
7. Display fail
In this section, we will look into some common
End problems in computer science and wil specify its solution by
Variables: pass, fail, no of students, marks writing an algorithm and pseudocode, and drawing its corresponding flowchart.
1.6.1 Find Minimum in a List
Consider the following requirement specification.
1.5.4 Programming Languages You are given a list of numbers from which you are supposed to find the minimum
to computations performed
that can be
value. An algorithm is
Apragrammg damgauage is a language specihcally designed express that control the behav1our of a system, required for entering the numbers in the list and then calculate the minimum value. The count of numbers to
bya computer. Programming languages are used to create programs be entered in the list should also be asked from the user
to express algorithms,or as a mode of human communication.
Usaly, programming languages have a vocabulary of syntax and semantics for instructing a computer Before writing the algorithm, just visualize how it works. Takethe first mumber inthelist and call
it minimum. Compare the minimum's value with all other values in the list one
toperfom specific tasks. The tem programming language refers to high-level languages such as BASIC by one. The moment
you find a smaller element than the minimum, call it the minimum. Figure 1.2
(Beginners All-purpose Symbolic Instruction Code). C, C+, COBOL (Common Business Oriented Language),
this concept.
given below 1llustrates
FORTRAN (Fomula Translator), Python,Ada, and Pascal, to name a few. Each of these languages has a unique
set ofkeywords(wordsthatit understands) and a special syntax for organizing program instructions.
hough hghievel programming languages are easy humans to read and understand, the computer can
for
understand only machne language, which consists of only numbers. Each type of central processing unit
(CPU) has ts own unique machine language. Let MIN = 3, Compare MIN with every element in the list ane by one
n between machine languages and high-level languages, there is another type of language known as
assenmbly language. Assembly languages are similar to machine languages, but they are much easier to The ste w
program because they allow a programmer to substitute names for numbers. MIN<5, so no change
However, imespective of the language that a programmer uses, a program written using any
anguage has to be converted into machine language so that the computer programming
can understand it, There are two
ways to do this: compile the program or interpret the MIN< 9, so no change
program.
When planning a software solution, the software
waich programming language to use? Many development team often faces a common question
ts own suengths and weaknesses. Python can programming languages are available today and each one has
be used to write
MIN< 1, so set MIN = 1
an efficient
casy to wrle and understand; some languages are code, whereas a code in BASIC 15
are well known to the programmers, whereas otherscompiled, whereas others are interpreted; some languages MIN<4,
paricular application at hand is a are
completely so no change
daunting task.
new.
Selecting the perfect language for a
Theselecton of language for writing a
The type of computer hardware and program depends on the
following factors: MIN < 7 so no change
*The typeof software on which the
program. program is to be executed.
The expertise and
availability of the
Features to write the programmers. MIN<2, so no change
application.
The built-in features that
Lower development andsupport the development of software
that are
maintenance
Stability and capability to support evencosts. reliable and less prone to crash. MIN< 6, so no change
more than the
expected simultaneous users. Flgure 1.2 Finding minimum value in a list
15
Algorithmic Problem Solving
with Python
Programming
and
Problem Soving
14 through
in a list 1s
demonstrated
gh
for solving the problem
ot hnding
the
minimum

Pseudocode 1.1
The step-wise approach Pseudocode
1.1.
Flowchart 1.1, and Read the count of numbers as N
Algorithm 1.1, Set I
Read the first element as MIN
Algorithm 1.1 While I <N 1
Read the next number as NUM
Step 1: start numbers as N
IF MIN < NUM
count of
the
Step 2: READ Set MIN = NUM
I = 8
Step 3: SET element as MIN Set I I +1
the first
Step 4: READ 6-8 WHILE I <N Print MIN
Step 5: REPEAT Steps NUN
next number as End
READ the
Step NUM Variables: I, N, NUM, MIN
Step 7: IF MIN <
SET MIN = NUM

I+1
SET I 1.6.2 Insert a Card in a List of Sorted Cards
=
Step 8:
PRINT MIN
into a sorted list of numbers. For this,
Inserting a card in a list of sorted cards is same as inserting an element
Step 9:
Step 10: End 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.3 given below illustrates this comcept
Flowchart 1.1

Start Position Element To Be inserted


Original List
Read the count 7>11
of numbers as N
7>10* 10
7>9 10
SET I =
7>6 T0

Figure 1.3 Inserting a number in a sorted list


card in a list of sorted cards is
Read the first
element as MIN
The step-wise approach for solving the problem of inserting a represented
through Algorithm 1.2, Flowchart 1.2, and Pseudocode 1.2.
Algorithm 1.2
NO
Is I cN 12 Print MIN Step 1: Start
YES READ Number of elements in the sorted list as N
Step 2
Kead tne next Step SET I=0
number as NUM Stop Step 4: REPEAT Steps 5 and 6 WHILE I < N

Step 5 READ the Sorted 1ist element as List[I]


NO Step SET I I+1
Is MIN NUM? Step READ Element to be inserted as X
Step 8:SET 1 N-1
YES
Step 9: REPEAT Step 10 and 11 WHILE I = 0 AND X<List[I]
SET MIN= NUM Step 10 List[I+1] = List[I]
Step 11 SET I I 1
Step 12: List[I+1] X
SET I I1 Step 13 End
17
Problem Solving and
Programming with Python ote f Algorithmic Problem Solving
16

1.6.3 Guess an Integer Number in a Range


Flowchart 1.2 Let us play a game. While playing this game you will be able to appreciate how two different solutions to the
rus r buez
same problem can
vary so much in terms of efficiency. The game is that the computer will randomly select
Start an integer from 1 to N and ask you to guess it. To help you guess the number correctiy, 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.
Read Number of There are two ways to succeed in this game. First is the linear search and second is the binary search. In
elements in the
linear search, you will guess the number as 1, then 2, then 3, then 4, and so on, you until guessed the right
sorted 1 i s t as
number. So you are guessing all the numbers as if they were lined up in a row. This techniqueis fine but just
wonder how many guesses you would have to make. If the computer selects N, you
small
would need Nguesses. If
SET I
Nis 1 then, of course, you will make it in the very first guess itself. Evenif Nis a
is a
numberlike 5 or 10,
then it is still fine but just imagine what will be the number of guesses if N large mumber.
Now let us explore the binary search technique. Since the computer tells whether guess istoo low,
you the a
VO
Read Element t too high, or correct, it is better to start by guessing N/2. If the number selected by
computer islessthan
I sI <N as X N/2, then using the computer's information that the guess is too high. you can eliminate all the mumbersfrom
be insert
N/2 to N in one If the number selected by the
just go. computeris
greater than N/2,then allelementsfrom
YES
par to bre sdl mot hua 1 through N/2 are eliminated right away. So with one guess you have narrowed down possible
your guesses
the sorted list/ SET I N1 by half. Isn't that interesting and an intelligent move? Keep on cutting down the set of possible mumbers by
SET I I+1Read
element as L i s t [ I half with every guess that you make.
While linear search technique required N guesses to win the game, binary search technique, on the other
hand, make you win (or find the number) in at most log N+I guesses. The following table shows the
can

Is I 0 AND NO maximum number of guesses for linear search and binary search for a few number sizes:
SET List[il X
X<List[I]?
Max Linear Search Guesses Max Binary Search Guesses
VALUE OF N
Stop 10
10
SET List[I+1] = List[I] 100 100
hSET I =I - 1
1,000 1,000
|10,000 10,000
100,000 100,000
g h gnivior not lopoxgge oeivegofe erll 1,000,000 20
1,000,000
Pseudocode 1.2 an integer number in range is
The step-wise approach for solving the problem of guessing
a given
demonstrated through Algorithm 1.3, Flowchart 1.3, and Pseudocode 1.3.
Start
Read Number of elements in the
Set I=
sorted 1ist as N Algorithm 1.3
WHILE I <N
Step 1: Start
Read the Sorted 1ist element
Set I =I+1
as List[I] Step 2: SET I 0
numbers as N
Read element to be
inserted as X
Step 3: READ the range of
selected number from 1 to N
Set I = N-1 Step 4: SET NUM as a random.ly
WHILE I >= 0 AND Step 5: READ VAL as a value guessed by the user
List[I+1] = List[I)
X<List[I] SET I I+1
step 6:
Set I = I 1 Step 7: IF VAL NUM
List[I+1] =X THEN PRINT "YOU WIN.. You guessed the number in Ith Turn
End Go to Step 10
Algorithmic Problem Solving 19
Programming with Python
Problem Solving and
18

RG bpop
vsie Pseudocode 1.3
VAL >NUM
Step 8: I FPRINT "VALUE TOO HIGH..
PLAY AGAIN.."

THEN Start
Go to Step 5
Set I =
IF VAL <NUM
Step 9: Read the range of numbers as N
TOO LONW PLAY AGAIN.
THEN PRINT "VALUE Set NUM as a randomly selected number from 1 to N
Go to Step 5 owhum 75d Read VAL as a value guessed by the user
Step 10: End Set I = I +1

While VAL = NUM


IF VAL = NUM
THEN PRINT "YOU WIN... You guessed the number in I Turn
Exit
Flowchart 13 olqxo a 1919 ELSEIF VAL NUM
THEN PRINT "VALUE TO0 HIGH.PLAY AGAIN...
ued e J99T100 10 g t co ELSE
Start THEN PRINT "VALUE TO0 LOW PLAY AGAIN"
End
i nbotEiiie s1 SV nguondh

SETI e slog 2s ow zs ( )
1.6.4 Tower of Hanoi
9Upindosl dozs52 1892 sltiw
Read the range The tower of Hanoi is one of the main applications of recursion. It says, ifyou can solve n- cases, then you
of numbers as N can easily solve the nth case'.
We will discuss the tower of Hanoi problem one, using
two, then three rings.
and finally Figures1.4(a)and
(b) explain the working of the tower of Hanoi problem using one and two rings.
SETNUM as a randomly T0 BUJAV
selected number from 1 to N
OF

Read VAL as a value


guessed by the Step 1) (Step 1) (Step 2)
useraoo.or ooo,0
SET I 1 +1
000.00
00.000 000.000.
(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
pole and then move ring 2 from source to the destination
Is VAL NUM? PRINT "YOU WIN you Stop
then simply move the ring
from source to the destination.) Finally move ring 1 from spare to the destination.)
guessed the number
in Ith Turn" (a) (6)
Figure 1.4 Working of tower of Hanoi problem using one and two rings
PRINT VALUE
T00 LOW
IsVAL NUM? Now, consider at Figure 1.5 which shows three rings mounted on pole A. The problem is to move all these
PLAY AGAIN.. 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.
PRINT"VALUE Rules of this problem include
TOO HIGH.,.
PLAY AGAIN,..7 Only one disk can be moved among the towers at any given time.
Only the "top" disk can be removed.
N o large disk can sit over a small disk.
and Programming
with Python
Problem Soving Algorithmic Problem Solving 21
20
3 Disks
(1) Flowchart 1.4
Begin Hanoi (disk, source, dest, spare)
BC
(4)
(2)
diske-1
(7) Hanoi (disk-1, source, Move disk from
(5) 6) spare, dest) source to dest

Hanoi problem Move disk from


the Tower of
Figure 1.5 Solving source to dest/

In our case, A 1S the source pole, C 1s the destination pole, and B


spare pole.
We will besolving this using
a
we will first shift the upper
two rings (n-1 rings) Hanoi (disk-1,
all the three rings from A to C,
isthe spare pole. To transfer (refer to Steps 1, 2 and 3 of Figure 1.5).
Now thatn-1 rings have been spare, dest, source)
fromthe source pole to the spare pole
moved from the source pole (A) to the destination pole (C)
removed from pole A, the nth ring final easily
can be
as well as pole
(refer to Step 4 of Figure 1.5). The step is to move the n-I rings from the spare pole (B)
and 7 of Figure 1.5). (End Hanoi
(A) to the destination pole (C) (refer to Steps 5, 6, be
A to C using B given as
Tosummarize, the solution to our problem of moving n rings from
as can
spare
Pseudocode 1.4
Base case: If n=1
Move the ing from A to Cusing B as spare dorgopeR o19w/0 erit22u oerb irg s / Begin Procedure Hanoi (disk, source, dest, spare)
Recursive case: dto rwot oifs to aaitow ar nrelq IF disk = 1
Move n-1 rings from A to B using C as spare THEN Move disk from source to dest
Move the one ring left on A to C using B as spare ELSE
CALL Hanoi(disk-1, Source, spare, dest)
We can conchudethat the steps to solve the tower of Hanoi problems are: Move disk from source to dest
Step 1-Move n-1 disks from source to the spare polee
CALL Hanoi(disk -1, spare, dest, source)
Step 2-Move nth disk from source to destination pole
End Procedure Hanoi (disk, source, dest, spare)
Step 3-Move n-1 disks from the spare pole to the destination pole
The step-wiseapproach for solving the problem of tower of Hanoi is demonstrated through Algorithm 1.
Flowchart 14, and Pseudocode 14. the implementation of the solution of the
Note: Refer to Program 4.17 for the code demonstrating
tower of Hanoi problem.

Algorithm 14 Hanoi(disk, source, dest, spare) Types of Errors Types of errors


Step 1: Begin While writing programs, very often we get errors in
Step 2: 1 disk = 1 errors if not removed will either
our programs. I hese
THEN Go to step 3B erroneous output o r will not let the compiler
give
ELSE to compile the program. These errors are broadly Run-time Syntax Linker Logical
Go to step 4 classified under four groups as shown in igure l.6. errors TOrs errors errors
Step 3: Move disk from sOurce to As the name suggests, run
dest and then Go to Run-time Errors 1.6 Types of errors
Step 4: CALL Hanoi(disk-1, Step 7 Figure
source, spare, dest) time errors occur when the program is being run
Step 5: Move disk from source illegal operations like
to dest executed. Such errors occur when the program performs some
Step 6: CALL Hanoi(disk-1,
Step 7: End spare, dest, source) dividing a number by zero
opening a file that already exists
Programming
with Python
Problem Solving and
pAlgorithmic Problem Solving 23

lack of free memory space numbers

finding square
or logarithm of negative
execution, so the
code must be
written in such a way that it handles Exercises
terminate program
Run-time errors may
terminating
it u n e x p e c t e d l y Fill in the blanks
e r r o r s rather
sorts ot unexpected
generated when rules
of a progran
all
as compile-time
errors) are amming A jS a set of instructions that tells the 3. symbol is always the first and the last
errors (also
known
program line by line. The moment
the The
Syntax Errors Syntax (executes) each
instruction in the
computer how to solve a particular problem. symbol in a flowchart
violated. Python interprets execution of the program.
language are error, it stops
further 2. Algorithms are mainly used to achieve i s a form of structured English that describes
interpreter
encounters a syntactic rules of the programmint
with 3. and statements are used to change
are those errors which may comply ning algorithms.
Semantic errors the sequence of execution of instructions.
Semantic o r Logical Errors which is obviOusly not correct. For example, if you wri
write a 10 is used to express algorithms and as a mode
undesirable output Python will subtrars
language but gives an unexpected and the- symbol.Then 4. is a formally defined procedure for of human communication
of writing+ symbol, you put
program to add two numbers but instead
But, actually the output is difterent
from what you expected. performing some calculation. 11.
The process of dividing an algorithm into modules/
the numbers and returns
the result. and programmers . statements are used when the outcome of the functions 15 called
not detected by the compiler,
code. Such errors are
Logical errors are errors in the program locate and rectity the errors. Logical errors occur due to
process depends on some condition. 12. i s a technique of solving a problem by
line or use a debugger to 6. Repetition can be implemented using constructs such
must check their code line by breaking it down into smaller and smaller sub-
incorrect statements As and problems until you get to a small enough problem
linker is not able to find the function
definition for a given prototype 7. A complex algorithm is often divided into smaller that it can be easily solved.
Linker Errors These errors ocCur when the
units called

Summary State True or False

Programming means writing computer programs. While An algorithm 1s analysed to measure its performance in 1. An algor+thm solves a problem in a finite numberof steps. 6 Terminal symbol depicts the ffow of control of the
programming, the programmers takes an algorithm and terms of CPU time and memory space required to exe 2. Flowcharts are drawn in the early stages of program
code the instructions in a particular programming lan- cute that algorithm. formulating computer solutions. 7. Labelled connectors are square in shape.
guage, so that it can be executed by a computer. Sequence means that each step of the algorithm is exe 3. The main focus of pseudocodes is on the details of 8 The outputs of each step of an algorithm should be
An algornthm provides a blueprint to writing a program cuted in the specified order. the language syntax. unambiguous. This means that is should be precise.
to solve a particular probiem Decision statements are used when the outcome of the 4. Algorithms are implemented using a programming 9 You can have maximum one function in a algorithm.
In the course of processing, data 1S read irom an input process depends on some condition. language. 10. Pseudocode is written usng the syntax of a particular
device, stored in computer's memory for further pro- Iteration or Repetition involves executing one or more 5. Repetition means that each step of the algorithm is programming language.
cessing and then the result of the processing is written executed in a specified order.
steps for a number of times, can be implemented using
to an
output device constructs such as the while loops and for loops.
The data is stored in the computer's memory in the form Programming languages have
of variables or constants. a vocabulary O syi Multiple Choice Questions
and semantics for
For a complex problem, its instructing a computer to perto
algorithm is often divided specific tasks. 1. Algorithms should be (c) subroutines
intosmaller units called functions (or modules). (6) unambiguous (d) all of these
Pseudocode facilitates designers focus (a) precise
Algonthm validation ensures that the
algorithm will
to on the
loge (c) clear (d) all of these 6. A single operation which when executed convert one
work coectly irespective of the programming of the algorithm without getting bogged down by
lan- details of language 2. To check whether a given number is even or odd, you state to other is called
guage in which it willbe syntax.
implemented. will use which type of control structure? a) instruction (6)program
(a) sequence (b) decision ()software (d)control
Glossaryy (C) repetition (d) all of these 7 Algorithm is validated to
3. Which one of the following is a graphical or symbolic (a) measure its CPU time
Program A set of instructions that tells the representation of a process?
to solve
particular problem.
a computer how Pseudocode A compact and (b) measure the memory consumed
Algorithm A step by step nstructions that informal (a) algorithm (b) flowchart (c)check if it is correct
tells the
description of an algorithm that uses the hign ural
computer how to solve a particular conventions of a struc (c) pseudocode (d)program (d) all of these
Programming The act of wrting problem. programming
Flowchart A diagrammatic language. 4 In a flowchart, which symbol is represented using a 8 Programming languages have a vocabulary of_
Instruction A Sngle operation programs.
which when the representation
sequence of steps that must be that ilust
ates rectangle? tor instructing a computer to perform specific tasks.
convert one state to0 other executed performed to so (a) terminal (b) decision
problem. (a) syntax (6) semantics
Modularization The process of dividing an RecursioD A (C) activity (d) input output ()both of these (d) none of these
into modules/functions. algorithm breaking it downtechnique of solving a proble D 5. Which of the following details are omitted in 9. Syntax and semantics of a language are strictly
into smaller and
Programming language A
until you get to small smaller pseudocodes?
enough problem sub-proD
language checked in
to express
computations that can be specihcally
periormed
designed casily solved.
a
that it (a) variable declaration (a) algorithm (b) flowchart
by a computer. Ca (b) system specitie code (c)pseudocode (d) program
24 Problem Solving and Programming with Python

Review Questions
draw a flowchart that
11. Write algorithm and
an
1. Define an algorithm. How is it useful in the
context the user
an employee. Prompt
calculates salary of
of software development? and DA. Add
to enter the
Basic Salary, HRA, TA,
2. and compare the approaches for designing
Explain calculate the Gross Salary. Also
these components to
an algorithm. from the Gross Salary
to be paid
deduct 10% salary
3. What is modularization? as tax.
repetition, and decision algorithm and a
4. Explain sequence, Draw a flowchart and write an
12.
Also give the keywords used in each type problem statements
psuedocode for the following
statements.

of statement. (a) Cook maggi


of a5
With the help of an example, explain the use a
0 0 9ag 0 e g
(b)Cross road
flowchart. items purchased
flowchart different from an algorithm?
(c) Calculate bill of is positive or
6. How is a whether a number

need to have both of them


for program (d)To find out
Do we
negative
development? the screen
(e) Print "Hello" five times
on

7. What do you understand by the term pseudocode? ( Find area of a rectangle


Diferentiate between algorithm and pseudocodes. u
Convert meters into centimeters
9. Give the characteristics of an algorithm. g)
(h) Find the sum of first 10 numbers
term recursion?
10. What do you understand by the
oalsso ounT slsle

.atouloe socmo gnillpmme

gaahsotpego
obo Soiicogearibotuoo

nelesuoeoorosleu
o blaorletog

Answers
Fill in the Blanks toittaga
iledunge tolaordigg s wolollto
1. Program
2. software reuse
re4, Algorithm 20 0 7. functions or modules 10. Flowcharts
5. Decision
3. Decision, repetition
6. while,
8. Terminal symbols 11. Modularization
do-while, and for 9. Psuedocode 12. Recursion
loops
State True or False
True 2. True 3. True 4. False 5. False 6. False 7. False 8. False 9. False 10. False
Multiple Choice Questions
1. (d) 2. (b) 3. obepo
6) 4. ()5. (d) 6. (a) 7. (c) 8. (c) 9. (d)
stioo r

You might also like