Py Unit - 1
Py Unit - 1
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-Khowarizmi, a
Persian mathematician in the ninth century. Al-Khowarizmi Algorismus (in
Latin) Algorithm.
An algorithm is a well-defined computational procedure consisting of a set of
instructions that takes some value or set of values, as input, and produces some
value or set of values, as output. In other word, an algorithm is a procedure that
accepts data; manipulate them following the prescribed steps, so as to eventually fill
the required unknown with the desired value(s).
People of different professions have their own form of procedure in their line
of work, and they call it by different names. For instance, a cook follows a procedure
commonly known as a recipe that converts the ingredients (input) into some culinary
dish (output), after a certain number of steps.
1.2.1 The Characteristics of a Good Algorithm
££ Precision : the steps are precisely stated (defined).
££ Uniqueness : results of each step are uniquely defined and only depend
on the Input and the result of the preceding steps.
££ Finiteness : the algorithm stops after a finite number of instructions are
executed.
££ Effectiveness : algorithm should be most effective among many different
ways to solve a problem.
££ Input : the algorithm receives zero or more finite number of inputs.
££ Output : the algorithm produces one or more finite number of outputs.
££ Language Independent : the algorithm is not dependent of any
language
££ Correctness : Algorithm returns correct output in a finite number of
steps
1. 4 Problem Solving and Python Programming
A sequence is a series of steps that occur one after the other, in the same order
every time. Consider a car starting off from a set of lights. Imagine the road in front
of the caris clear for many miles and the driver has no need to slow down or stop.
The car will start in first gear, then move to second, third, fourth and finally fifth. A
good driver (who doesn‘t have to slow down or stop) will move through the gears in
this sequence, without skipping gears.
Step 1: Start
Step 2: get a,b
Step 3: calculate c = a + b
Step 4: Display c
Step 5: Stop
Start
Declare variables a,b and c.
Read variables a,b and c.
If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Stop
Example - 2
Find the roots of a Quadratic equation: ax^2 + bx + c = 0
Start
Declare variables a, b, c, D, x1, x2, rp and ip;
Calculate discriminant
D ← b2-4ac
If D ≥ 0
r1 ← (-b+√D)/2a
r2 ← (-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp ← -b/2a
ip ← √(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Stop
Example - 3
Find the factorial of a number.
Algorithmic Problem Solving 1.11
Start
Declare variables n, factorial and i.
Initialize variables
factorial ← 1
i←1
Read value of n
Repeat the steps until i = n
factorial ← factorial*i
i ← i+1
Display factorial
Stop
Example - 4
Check whether a number is prime or not
Start
Declare variables n, i, flag.
Initialize variables
flag ← 1
i←2
Read n from the user.
Repeat the steps until i=(n/2)
If remainder of n÷i equals 0
flag ← 0
Go to step 6
i ← i+1
If flag = 0
Display n is not prime
else
Display n is prime
Stop
to be verbose and ambiguous, and is rarely used. Pseudo code and flowcharts are
structured ways to express algorithms. Pseudo-code is something that represents
the algorithm through structured human language. Flowchart is something that
represents the algorithm graphically. Programming languages are intended for
expressing algorithms in a form that can be executed by a computer.
1.3.1 Algorithm as Step-Form
It is a step - by - step procedure for solving a task or problem. The steps must
be ordered, unambiguous and finite in number. It is English like representation of
logic which is used to solve the problem.
Some guidelines for writing Step-Form algorithm are as follows:
££ Keep in mind that algorithm is a step-by-step process.
££ Use begin or start to start the process.
££ Include variables and their usage.
££ If there are any loops, try to give sub number lists.
££ Try to give go back to step number if loop or condition fails.
££ Use jump statement to jump from one statement to another.
££ Try to avoid unwanted raw data in algorithm.
££ Define expressions.
££ Use break and stop to terminate the process.
For accomplishing a particular task, different algorithms can be written. The
different algorithms differ in their requirements of time and space. The programmer
selects the best suited algorithm for the given task to be solved.
Let as look at two simple algorithms to find the greatest among three numbers,
as follows:
Algorithm
Step 1: Start.
Step 2: Read the three numbers A,B,C.
Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.
Step 4: Compare A and C. If A is greater, output -A is greater else output -C is
greater.
Step 5: Compare B and C. If B is greater, output -B is greatest else output -C
is greatest.
Step 6: Stop.
Algorithmic Problem Solving 1.13
1.3.2 Pseudocode
What is pseudocode?
“Pseudo” means initiation or false.
“Code” means the set of statements or instructions written in a programming
language.
Pseudocode is also called “Program Design Language [PDL]”.
Pseudocode is an informal way of programming description that does not
require any strict programming language syntax. It is used for creating an outline or
a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details. System designers write pseudocode to ensure that programmers
understand a software project’s requirements and align code accordingly.
1.3.2.1. How can one describe a pseudocode?
Pseudocode is not an actual programming language. So it cannot be compiled
into an executable program. It is composed of simple English language syntaxes to
write code for programs before it is actually converted into a specific programming
language that cannot be understood by the computer. This is done to identify top
level flow errors, and understand the programming data flows that the final program
is going to use. This helps to save time during actual programming as conceptual
errors have been already corrected .
Firstly, program description and functionality is gathered and then pseudocode
is used to create statements to achieve the required results for a program. Detailed
pseudocode is inspected and verified by the designer’s team or programmers to match
design specifications. Catching errors or wrong program flow at the pseudocode
stage is beneficial for development as it is less costly than catching them later. Once
the pseudocode is accepted by the team, it is rewritten using the vocabulary and
syntax of a programming language. The purpose of using pseudocode is an efficient
key principle of an algorithm. It is used in planning an algorithm with sketching out
the structure of the program before the actual coding takes place.
1.3.2.2. Rules for writing Pseudocode
1. Write one statement per line
2. Capitalize initial keywords (READ, WRITE, IF, WHILE, UNTIL).
3. Indent to show hierarchy.
1. 14 Problem Solving and Python Programming
Example - 2
Pseudocode which will accept two numbers from user and calculate
their sum and display the result.
Begin
Number s1,s2,sum
output(“Input number1: ”)
Input s1
output(“Input number2: ”)
Input s2
sum=s1+s2
Output sum
End
Algorithmic Problem Solving 1.15
Example - 3
Write a pseudocode to calculate and print the class average.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.
Example - 4
Pseudocode which will accept input from the user and calculate the
area and perimeter of a rectangle and execute the output on the screen.
Begin
Number b1,b2,area,perimeter
Input b1
Input b2
area =b1*b2
perimeter=2*(b1+b2)
Output area
Output perimeter
End
Example - 5
What will be the output of the following pseudocode ?
Integer i
Set i = 3
do
print i + 3
i=i-1
while(i not equals 0)
end while
1. 16 Problem Solving and Python Programming
Example - 6
Write a pseudocode that accepts two numbers from the user (dividend
and divisor), testing to make sure that the divisor number is not zero, and
displaying their quotient.
Declare variables: dividend, divisor, quotient
Prompt user to enter dividend and divisor
Get dividend and divisor
IF divisor is equal to zero, THEN
DO
Display error message, “divisor must be non-zero”
Prompt user to enter divisor
Get divisor
WHILE divisor is equal to zero
ENDIF
Display dividend and divisor
Calculate quotient as dividend/divisor
Display quotient
Example - 7
Pseudocode which will determine a student’s final grade and indicate
whether he is getting pass mark or fail mark. The final grade is calculated
as the average of three marks.
Input a set of 3 marks
Calculate their average by summing and dividing by 3
if average is below 50
Print “FAIL”
else
Print “PASS”
Example - 8
Write a pseudocode that accepts ‘n’ value of input from the user and
calculate the sum of n numbers.
Algorithmic Problem Solving 1.17
Sequential
Although it looks like a ‘Q’, the symbol is
Access Storage
supposed to look like a reel of tape.
(Magnetic Tape)
Even though many symbols are available, the most commonly used
symbols in the flowchart are:
Advantages of flowcharts
1. Communication - Flowcharts are better way of communicating the logic
of a system.
2. Effective analysis - With the help of flowchart, problem can be analysed
in more effective way.
3. Proper documentation - Flowcharts are used for good program
documentation, which is needed for various purposes.
4. Efficient Coding - Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging - Flowchart helps in debugging process.
6. Efficient Program Maintenance - The maintenance of running program
becomes easy with the help of flowchart.
Advantages of flowchart over pseudo code
££ Flowcharts provide an easy method of communication about the logic
and offer a good starting point for the project because they are easier to
create than pseudocode in the beginning stages.
££ Pseudocode provides a beneficial bridge to the project code because it
closely follows the logic that the code will.
Algorithmic Problem Solving 1.23
Disadvantages of a flowcharts
££ Complex logic Sometimes, the program logic is quite complicated. In
that case, flowchart becomes complex and clumsy.
££ Alterations and Modifications - If alterations are required the flowchart
may require re-drawing completely.
££ Reproduction- As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
Disadvantages of flowchart over pseudo code
Forming a flowchart is a time consuming work and the branching and looping
statements are difficult to show here while in pseudo code it was easy to show the
branches and loops and are clearly understandable.
Simple Examples
Example - 1
Write an algorithm, pseudocode and flowchart to find the sum of two numbers.
Algorithm
Start
Enter the input value A and B
Find Sum = A + B
Display the value of Sum
Stop
Pseudocode
ENTER the input value A and B
Find Sum
Sum = A + B
PRINT Sum
STOP
1. 24 Problem Solving and Python Programming
Flow chart
Example - 2
Write an algorithm, pseudocode and flowchart to find the greatest of
three numbers.
Algorithm
Start
Get A, B, C
if(A>B) goto (A>C) else goto (B>C)
If(A>C) print A else print C
If(B>C) print B else print C
Stop
Pseudocode
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
Algorithmic Problem Solving 1.25
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
Flowchart
Example - 3
Write an algorithm,pseudocode and draw a flowchart that will read
the two sides of a rectangle and calculate its area.
Algorithm
Start
Input Length,Breadth
Area = Length*Breadth
Print Area
Stop
1. 26 Problem Solving and Python Programming
Pseudocode
Read Length,Breadth
CALCULATE Area = Width*Length
Print Area
Flowchart
Example - 4
Write an algorithm, pseudocode and flowchart to swap two variables
without using temporary variables.
Algorithm
Start the program
Read the value of A,B
To swap without using another value is
A←A+B
B←A-B
A←A-B
Print the values of A and B
Stop
Algorithmic Problem Solving 1.27
Pseudocode
SET initial A,B
READ the value A,B
To interchange the value use
A=A+B
B=A-B
A=A-B
WRITE the values of c,d
Flowchart
Example - 5
Write an algorithm, pseudocode and flowchart to generate the
fibonacci series.
Algorithm
Start
Assign a ←0,b←1,sum←0
READ n
Input i←2
IF(i<=n)
Sum =a+b
a=b
b=sum,i++
Print sum
Go to IF condition
ELSE
Stop
1. 28 Problem Solving and Python Programming
Pseudocode
Start
Declare variable a,b,c,n,i
Initialize variable a=1, b=1, i=2
Read n from user
Print a and b
Repeat until i<n
c=a+b
print c
a=b, b=c
i=i+1
Stop
Flowchart
Algorithmic Problem Solving 1.29
Example - 6
Write an algorithm, pseudocode and flowchart for calculating area and
circumference of a circle.
Algorithm
Start
get r value
Calculate A=3.14*r*r
Calculate C=2.3.14*r
Display A,C
Stop
Pseudocode
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
END
Flowchart
1. 30 Problem Solving and Python Programming
Example - 7
Write an algorithm, pseudocode and flowchart for calculating simple
interest.
Algorithm
Start
get p,n,r value
Calculate
SI = (p*n*r)/100
Display S
Stop
Pseudocode
BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END
Flowchart
Algorithmic Problem Solving 1.31
Example - 8
Write an algorithm, pseudocode and flowchart to check leap year or
not.
Algorithm
Start
get y
if(y%4==0) print leap year
else print not leap year
Stop
Pseudocode
BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END
Flowchart
1. 32 Problem Solving and Python Programming
££ Iteration ££ Recursion
Iteration
Iteration is a process wherein a set of instructions or structures are repeated in
a sequence, a specified number of times or until a condition is met. Once a problem
is clear then the logic of the solution could be implemented using an iteration where
it could run multiple times to achieve a specific outcome
1. for loop
2. while loop
Syntax for For
FOR( start-value to end-value) DO
Statement
...
ENDFOR
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
1.4 Recursion
Recursion is a technique in which a function calls itself repeatedly until a
concluding situation happen. A function which utilizes this technique is called a
recursive function.
A recursive algorithm is an algorithm which calls itself with “smaller (or
simpler)” input values, and which obtains the result for the current input by applying
simple operations to the returned value for the smaller (or simpler) input. More
generally if a problem can be solved utilizing solutions to smaller versions of the
same problem, and the smaller versions reduce to easily solvable cases, then one can
use a recursive algorithm to solve that problem.
1. 38 Problem Solving and Python Programming
Pseudocode
BEGIN READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Algorithmic Problem Solving 1.41
Flowchart
Flowchart
1. 44 Problem Solving and Python Programming
10 10 4
100 100 7
1000 1000 10
10,000 10,000 14
1,00,000 1,00,000 17
1,000,000 1,000,000 20
Algorithm
Step 1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then Print Guess is hit
Step 6: Else Print Guess not hit,Print hidden
Step 6: Stop
Pseudocode
BEGIN
COMPUTE hidden=random value in range
READ guess
IF guess=hidden, then
PRINT Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
1. 46 Problem Solving and Python Programming
Flowchart
Rules
££ 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.
Figure 1.4 Step by Step Moves in ESolving Three Disk Tower of Hanoi Problem
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve
this problem with lesser amount of disks, say → 1 or 2. We mark three towers with
name, source, destination and aux (only to help moving the disks). If we have only
one disk, then it can easily be moved from source to destination tower.
If we have 2 disks
££ First, we move the smaller (top) disk to aux tower.
££ Then, we move the larger (bottom) disk to destination tower.
££ And finally, we move the smaller disk from aux to destination tower.
So now, we are in a position to design an algorithm for Tower of Hanoi with
more than two disks. We divide the stack of disks in two parts. The largest disk (nth
disk) is in one part and all other (n-1) disks are in the second part.
1. 48 Problem Solving and Python Programming
Our ultimate aim is to move disk n from source to destination and then put all
other (n-1) disks onto it. We can imagine to apply the same in a recursive way for all
given set of disks.
The steps to follow are
Step 1 - Move n-1 disks from source to aux
Step 2 - Move nth disk from source to dest
Step 3 - Move n-1 disks from aux to dest
A recursive Step based algorithm for Tower of Hanoi can be driven as follows:
Algorithm
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call T(n,Beg,Aux,End) recursively until n=0
Step 4.1: If n=0, then goto
Step 5 :else goto step 4.2
Step 4.2: T(n-1,Beg,End,Aux) T(1,Beg,Aux,End) , Move disk from source to
destination T(n-1,Aux,Beg,End)
Step 5: Stop
Pseudocode
BEGIN
READ n
CALCULATE move=pow(2,n)-1
FUNCTION T(n,Beg,Aux,End) Recursively until n=0
PROCEDURE
IF n=0 then,
No disk to move
Else
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move isk from source to destination
T(n-1,Aux,Beg,En )
END PROCEDURE
END
Algorithmic Problem Solving 1.49
Flowchart
££ Effectiveness ££ Feasibility
££ Input ££ Generality.
££ Output
5. Describe different notations in algorithm and classify each.
Algorithms can be expressed in many different notations, including Natural
Language, pseudo code, flowcharts and programming languages.
Natural language tends to be verbose and ambiguous, and is rarely used.
Pseudocode and flowcharts are structured ways to express algorithms.
Programming languages are intended for expressing algorithms in a form that
can be executed by a computer.
6. Define Pseudocode.
Pseudocode is an informal language used by programmers to develop algorithms.
Pseudocode is a “text-based” detail design tool.
Example
Enter value
If value greater than 10
Say “your number is greater than 10”
If value less than 10
Say “your number is lesser than 10”
Review Questions
1. Define an algorithm.
2. List the advantages of using an algorithm.
3. Write an algorithm to compute the factorial of a given number.
4. What are the characteristics of an algorithm?
5. Define pseudocode.
6. Write two characteristics of pseudocode.
7. List out the advantages and disadvantages of pseudocode.
8. Write the rules for writing a pseudocode.
9. Describe (i) Qualities of a good algorithm. (ii) Representation of an algorithm
10. Define flowchart.
11. What are the various symbols used in flowcharting? Give their pictor
representation.
12. Draw a flowchart to find the biggest among two numbers.
13. Draw a flowchart to find the sum of first N Natural numbers. 14. Draw a
flowchart to find the maximum of three integer numbers.
14. What are the basic logic structures used in writing structured programs?
Algorithmic Problem Solving 1.53