Unit I Algorithmic Problem Solving

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

UNIT I /Algorithmic

[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

UNIT I ALGORITHMIC PROBLEM SOLVING


Algorithms, building blocks of algorithms (statements, state, control flow, functions),
notation (pseudo code, flow chart, programming language), algorithmic problem solving,
simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range,
Towers of Hanoi.

1.1 ALGORITHM
An algorithm is a procedure (or) a set of instruction for solving a problem, based
on conducting a sequence of actions.

1.1.1 Characteristics of Algorithm:


An algorithm has following characteristics:
 In the algorithm each and every instruction should be precise and unambiguous.
 Instruction should not repeat infinitely.
 Algorithm should be written in sequence.
 It looks like normal English.
 After the instructions are executed, the user should get the required results.

1.1.2 Qualities of Good Algorithm:


The following are the primary factors that are used to analyze the quality of the algorithms,
S.N Factors Quality of Good Algorithm
o
1 Time To execute a program, the computer system takes
some amount of time. The lesser is the time
required, the better is the algorithm.
2 Memory To execute a program, computer system takes some
amount of memory storage. The lesser is the
memory required, the better is the algorithm.
3 Accuracy  Multiple algorithms may provide suitable or correct
solutions to a given problem, some of these may
provide more accurate results than others, such
algorithms may be suitable.
4 Sequence The procedure of an algorithm must form in a

PPG INSTITUTE OF TECHNOLOGY Page 1


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

sequence and some of the instruction of an algorithm


may be repeated in number of times of until a
particular condition is met.
5 Generability The designed algorithm must solve isolated problem
and more often algorithms are designed to handle a
range of input data to meet this criteria, so the
algorithms must be generalized.

1.1.3 Representation of Algorithms:


The Algorithms can be represented in several ways. Generally the programmers
follow one of the following ways to represent an algorithm.
I. Normal English
II. Flowchart
III. Pseudo code
IV. Decision Table
V. Program
S No. Representation Description
1 Normal English Algorithm can be represented as step by step procedures in
normal English, algorithms are easy to understand, read and
write.
2 Flowchart Flow chart is a pictorial representation of an algorithm.
Sequential steps in an algorithm can be represented as a
flowchart using standard symbols.
3 Pseudo code Pseudo code 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. 
4. Decision Table Decision tables are compact and precise ways of modeling
complicated logic. A decision table helps a lot in designing a
specific segment of a design.
5. Program The Algorithm can be represented as a program using any high
level language that becomes a program.

1.2 BUILDING BLOCKS OF AN ALGORITHM


I. Statements
II. Sequential Control

PPG INSTITUTE OF TECHNOLOGY Page 2


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

III. Selection or Conditional


IV. Repetition or Control flow
V. Functions

1.2.1 Statements:
 A statement can be termed as a single instruction/operation in an algorithm which
performs exactly single task.
 An algorithm is a series of specific steps (statements) which solve a particular
problem.
Example:
Most algorithms have parts:
 Description of problem
 Set up
 Parameters
 Execution
 Conclusion
The Simple example to find the sum of two numbers:
 Description of problem: To find the sum of two numbers.
 Set up: Two numbers required for addition and one variable for storing the results.
 Parameters:
o Read 1st Number.
o Read 2nd Number.
 Execution: Calculate the sum of the two numbers
 Result= a + b
 Conclusion: The desired result is sum.

1.2.2 Sequential Control:


Sequential control means that the steps of an algorithm are carried out in a sequential
manner, where each step is executed exactly once.

Example:
Algorithm to convert Centigrade to Fahrenheit

PPG INSTITUTE OF TECHNOLOGY Page 3


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Step 1: Read the temperature in degree Centigrade


Step 2: Convert the Centigrade to Fahrenheit using the formula
F= 9/5 * c+32
Step 3: Print the Celsius and Fahrenheit value

1.2.3 Selection or Conditional


In Selection Control only one of a number of alternative steps is executed based on
the condition.
Example 1:
Algorithm to find Greatest of two numbers
Step 1: Read first numbers A
Step 2: Read second number B
Step 3: IF(a>b) then
Print A is big
Else
Print B is big

Example 2:
Algorithm to find student grade system
Step 1 : Start
Step 2 : Read marks
Step 3 : If marks >= 80 then grade =A, go to step 7
Step 4 : If marks >= 60 and marks <=80 then grade = B, go to step 7
Step 5 : If marks >=40 and marks <=60 then grade = C go to step 7
Step 6 : Else Display failed
Step 7 : Display grade.
Step 8 : Stop.

1.2.4 Repetition or Control flow:

PPG INSTITUTE OF TECHNOLOGY Page 4


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 In Repetition one or more steps are performed repeatedly. This logic is used for
producing loops in program logic, when one or more instructions may be executed
several times.
 Repetition statements are also called loops, and are used to repeat the same code
multiple times in succession.
 The number of repetitions is based on criteria defined in the loop structure, usually a
true/false expression
 The three loop structures are:
 while loops
 do-while loops
 for loops
Example:
Read numbers and add them up until their total value reaches or exceeds a set value
represented by n
Step 1: WHILE (total < n)
Step 2: DO
Step 3: Read number
Step 4: Total = total + number
END DO
Step 5: Print total
1.2.5 Functions:
 For complex problems our goal is to divide the task into smaller and simpler tasks
during the algorithm design.
 A function is a group of statements that together perform a task.
 A function is a block of organized, reusable code that is used to perform a single,
related action.
 Functions provide better modularity for our application and a high degree of code
reusing.
Example:
Algorithm to find maximum number of an array
Step 1: Get a list of numbers L1,L2,L3….LN
Step 2: Set max = L1
Step 3: Take each element Li from the list and do the following

PPG INSTITUTE OF TECHNOLOGY Page 5


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Step 4: If max <Li


Set max = Li
If Li is last number from the list then
Print value stored in max
Else
Repeat same process starting from Step 3

1.3 NOTATION
1.3.1 Pseudocodes-Introduction
 Pseudo code 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. 
 “Pseudo” means imitation; “Code” means set of instructions.
Example
A pseudocode to add two numbers and display the results:
READ num1,num2
Result=num1+num2
WRITE result.

1.3.2 Basic Guidelines for Writing Pseudocode


Rules for Pseudocode
1. Write only one statement per line
2. Capitalize initial keyword
3. Indent to show hierarchy
4. End multiline structures
5. Keep statements language independent

1. One Statement Per Line


Each statement in pseudocode should express just one action for the computer.
Pseudocode
READ name, hoursWorked, payRate
gross = hoursWorked * payRate
WRITE name, hoursWorked, gross

PPG INSTITUTE OF TECHNOLOGY Page 6


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

2. Capitalize Initial Keyword


In the example below note the words: READ and WRITE. These are just a few of the
keywords to use, others include:
Pseudocode
READ name, hoursWorked, payRate
gross = hoursWorked * payRate
WRITE name, hoursWorked, gross

Rules for Variable Names


 Begin with lowercase letter
 Contain no spaces
 Additional words begin with capital
 Unique names within code
 Consistent use of names

3. Indent to Show Hierarchy


Each design structure uses a particular indentation pattern
Example
READ name, grossPay, taxes
IF taxes > 0
net = grossPay – taxes
ELSE
net = grossPay
ENDIF
WRITE name, net

4. End Multiline Structures


Each structure must be ended properly, which provides more clarity.

Example
READ name, grossPay, taxes
IF taxes > 0

PPG INSTITUTE OF TECHNOLOGY Page 7


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

net = grossPay – taxes


ELSE
net = grossPay
ENDIF
WRITE name, net

5. Keep Statements language independent


Design the pseudo code in such a way that it is free from some special requirements
of any programming languages.

1.3.3 Types of Logic Structure


 Sequence
 Selection
 Iteration
Sequence
Performing instruction one after another

The Selection Structure

PPG INSTITUTE OF TECHNOLOGY Page 8


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Performs action based on the condition given.

no

Pseudocode :
IF amount < 100
interestRate = .06
ELSE
Interest Rate = .10
ENDIF

The Looping /Iteration Structure


A loop statement allows us to execute a statement or group of statements multiple
times. That is executed repeatedly until condition fails. We may use the following keywords
to indicate looping structure.
WHILE/ENDWHILE
REPEAT/UNTIL
Example
count = 0
WHILE count < 10
ADD 1 to count
WRITE count
ENDWHILE
WRITE “The End”

1.3.3 Advantages & Disadvantages


Pseudocode Advantages
 Simple because it uses English-like statements
 Easily modified
 Implements structured concepts
 Done easily on Word Processor

PPG INSTITUTE OF TECHNOLOGY Page 9


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 No special symbols are used


Pseudocode Disadvantages:
 Not visual
 No accepted standard, varies from company to company
 Cannot be compiled and executed

1.3.4 Flow Chart –Introduction


Flowchart
A flowchart is a type of diagram that represents an algorithm, workflow or process,
showing the steps as boxes of various kinds, and their order by connecting them with arrows.
This diagrammatic representation illustrates a solution model to a given problem.

Basic symbols used in Flowchart


There are 6 basic symbols commonly used in Flowchart.
Indicates the starting or ending of the algorithm.
We draw a terminal symbol and write START inside it to
indicate the start of the flowchart.
1 Terminal
Similarly, we draw a terminal symbol and write STOP
inside it to indicate the end of the flowchart.

Use for Input/Output (I/O) operation i.e. taking input and


2 Input/Output
showing output.

Indicates any type of internal operations like


3 Process
initialization, calculation etc.
Use for asking questions that can have either TRUE or
FALSE (YES or NO) as an answer.
4 Decision
Example: Are you online?
Answer can be either YES or NO
Connectors are used to connect breaks in the flowchart.
5 Connector If a flowchart takes more than one page, then to connect
the flowchart between pages we use the connector.

PPG INSTITUTE OF TECHNOLOGY Page 10


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

6 Control Flow Show direction of flow.

Flowchart Rules
 Flowchart is generally drawn from top to bottom
 All boxes of flowchart must be connected with arrow.
 Only one flow line should come out from a process symbol.
 Flowchart must have start and end symbol.
 All flowchart start with a Terminal or Process symbol.
 Decision symbol have 2 exit points, one for YES (TRUE) and another for NO
(FALSE).

Example
Add 10 and 20
To solve this problem we will take a variable sum and set it to zero. Then we will take
the two numbers 10 and 20 as input. Next we will add both the numbers and save the result in
the variable sum i.e., sum = 10 + 20. Finally, we will print the value stored in the variable
sum.
Algorithm (in simple English)
 Initialize sum = 0 (PROCESS)
 Enter the numbers (I/O)
 Add them and store the result in sum (PROCESS)
 Print sum (I/O)

Flowchart

PPG INSTITUTE OF TECHNOLOGY Page 11


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Advantages and Disadvantages of Flowchart


Advantages of Using FLOWCHARTS:
 Communication: Flowcharts are better way of communicating the logic of a system
to all concerned or involved.
 Effective analysis: With the help of flowchart, problem can be analyzed in more
effective way therefore reducing cost and wastage of time.
 Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes, making things more efficient.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program becomes
easy with the help of flowchart. It helps the programmer to put efforts more
efficiently on that part
Disadvantages of Using FLOWCHARTS:
 Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy. This will become a pain for the user,
resulting in a waste of time and money trying to correct the problem
 Alterations and Modifications: If alterations are required the flowchart may require
re-drawing completely. This will usually waste valuable time.
 Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.

1.3.5 Programming Language Concepts

PPG INSTITUTE OF TECHNOLOGY Page 12


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 A programming language is a set of rules that provides a way of telling a computer


what operations to perform.
 A programming language is a set of rules for communicating an algorithm

1.3.5.1 What is a Programming Language?


 English is a natural language. It has words, symbols and grammatical rules.
 A programming language also has words, symbols and rules of grammar.
 The grammatical rules are called syntax.
 Each programming language has a different set of syntax rules.

1.3.5.2 Levels of Programming Languages


High-level program

class
class Triangle
Triangle {{
...
...
float
float surface()
surface()
return
return b*h/2;
b*h/2;
}}
Low-level program

LOAD
LOAD r1,b
r1,b
LOAD
LOAD r2,h
r2,h
MUL
MUL r1,r2
r1,r2
DIV
DIV r1,#2
r1,#2
RET
RET
Executable Machine code

PPG INSTITUTE OF TECHNOLOGY Page 13


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

0001001001000
0001001001000
1010010010011
1010010010011
1011001010110
1011001010110
1001...
1001...
1.3.5.3 What Are the Types of Programming Languages
 First Generation Languages
 Second Generation Languages
 Third Generation Languages
 Fourth Generation Languages
 Fifth Generation Languages

First Generation Languages


 Machine language
◦ Operation code – such as addition or subtraction.
◦ Operands – that identify the data to be processed.
◦ Machine language is machine dependent as it is the only language the
computer can understand.
◦ Very efficient code but very difficult to write.

Second Generation Languages


 Assembly languages
◦ Symbolic operation codes replaced binary operation codes.
◦ Assembly language programs needed to be “assembled” for execution by the
computer. Each assembly language instruction is translated into one machine
language instruction.
◦ Very efficient code and easier to write.

Third Generation Languages


 Closer to English but included simple mathematical notation.

PPG INSTITUTE OF TECHNOLOGY Page 14


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

◦ Programs written in source code which must be translated into machine


language programs called object code.
◦ The translation of source code to object code is accomplished by a machine
language system program called a compiler.
◦ Alternative to compilation is interpretation which is accomplished by a system
program called an interpreter.
 Common third generation languages
◦ FORTRAN
◦ COBOL
◦ C and C++
◦ Visual Basic

Fourth Generation Languages


 A high level language (4GL) that requires fewer instructions to accomplish a task than
a third generation language.
 Used with databases
◦ Query languages
◦ Report generators
◦ Forms designers
◦ Application generators

Fifth Generation Languages


 Declarative languages
 Functional: Lisp, Scheme, SML
◦ Also called applicative
◦ Everything is a function
 Logic: Prolog
◦ Based on mathematical logic
◦ Rule- or Constraint-based

1.4 ALGORITHMIC PROBLEM SOLVING

PPG INSTITUTE OF TECHNOLOGY Page 15


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 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.
 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).

Characteristics of an 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.
 Input – the algorithm receives input.
 Output – the algorithm produces output.
 Generality – the algorithm applies to a set of inputs.

1.4.1 Understanding the Problem:


 Before designing an algorithm we have to understand the problem completely.
 An input to the algorithm specifies an instance of the problem the algorithm solves.
 It is very important to specify exactly the range of instances the algorithm needs to
handle.

1.4.2 Ascertaining the Capabilities of the Computational Device:


 The second step is to ascertain the capabilities of the machine.
 Sequential algorithms: Instructions are executed one after another, one operation at a
time.Accordingly, algorithms designed to be executed on such machines.
 Parallel algorithms: The central assumption of the RAM model does not hold for
some newer computers that can execute operations concurrently.

1.4.3 Choosing Between Exact and Approximate Problem Solving:

PPG INSTITUTE OF TECHNOLOGY Page 16


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 The next decision is to choose between solving the problem exactly or solving it
approximately. Based on this, the algorithm is classified as exact and approximation
algorithms.
 There are three reasons to choose an approximation algorithm.
i. There are important problems that simply cannot be solved exactly for most
of their instances;
Ex: Extracting square roots, solving nonlinear equations and evaluating
definite integrals.
ii. Available algorithms for solving a problem exactly can be unacceptably
slow because of the probem’s intrinsic complexity.
iii. An Approximation algorithm can be a part of a more sophisticated algorithm
that solves a problem exactly.

1.4.4 Deciding on Appropriate Data Structures:


 Data structures refer to the types of data used and how the data are organized in the
program.
 Data come in different forms and types. Most programming languages provides
simple data types such as integers, real numbers and characters, and more complex
data structures such as arrays, records and files which are collections of data.
 Algorithm design techniques depend on the structuring data specifying a problem’s
instance.
ALGORITHM + DATASTRUCTURE = PROGRAMS

1.4.5 Algorithm Design Technique:


 Once the algorithm is designed, we need to specify it in some fashion.
 It is a general approach to solve problems algorithmically that is applicable to a
variety of problems from different areas of computing.
 There are two reasons for learning these techniques:
 They provide guidance for designing for new problems.
 They make it possible to classify algorithms according to an underlying design
data.

PPG INSTITUTE OF TECHNOLOGY Page 17


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

1.4.6 Methods of Specifying an Algorithm:


 A pseudo code which is a mixture of natural language and programming language like
constructs.
 It is more precise than natural language and its usage is similar to algorithm
descriptions.
 A flowchart is a method of expressing an algorithm by a collection of connected
geometric shapes containing descriptions of algorithm’s steps.
1.4.7 Proving An Algorithm’s Correctness:
 Correctness has to be proved for every algorithm.
 A common technique for proving correctness is to use mathematical induction
because an algorithm’s iterations provide a natural sequence of steps needed for such
proofs.
 The notion of correctness for approximation algorithm is less straightforward that it is
for exact algorithms.

Understand the Problem

Decide on: Computational means,


Exact vs. approximate solving,
Algorithm design technique

Design an algorithm

Prove Correctness

Analyze the algorithm

Code the algorithm


PPG INSTITUTE OF TECHNOLOGY Page 18
UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

1.4.8 Analyzing An Algorithm:


Efficiency is an important character of any algorithm.
 There are two kinds of algorithm efficiency:
 Time Efficiency.
 Space Efficiency.
 Another desirable characteristic of an algorithm is simplicity.
 Simpler algorithms are easier to understand and easier to program.
 Yet another desirable characteristic of an algorithm is generality.
There are two issues here:
 Generality of the problem the algorithm solves.
 The set of inputs it accepts.

1.4.9 Coding an Algorithm:


 Programming the algorithm by using some programming language.
 Formal verification is done for all small programs.
 Validity is done through testing and debugging.
 Inputs should fall within a range and hence require no verification.
 A good algorithm is a result of repeated effort and work.
 The program’s stopping or termination condition has to be set.

1.5 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS (ITERATION,


RECURSION)
1.5.1 Iteration
 An iterative statement is the set of statements/ instructions which are repeated for a
certain number of times until the specified condition fails.
 Example: Sum of numbers, factorial of a number
Example Algorithm to compute Factorial of a number using iteration:
Step 1: Start
Step 2 : Read the number ‘n’
Step 3 : Initialize fact=1, i=1

PPG INSTITUTE OF TECHNOLOGY Page 19


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Step 4 : while i<=n


fact=fact * i
I=i+1
Step 5 : Print fact
Step 6 : End

1.5.2 Recursion:
 A recursive function is one that calls itself again and again. It is used to call the same
function repeatedly.
 Recursion splits a problem into one or more simpler versions of itself.
 Example: Factorial of a number, Fibonacci series

Example Algorithm to compute factorial of a number using Recursion :


Step 1: Start
Step 2: Read the number ‘n’
Step 3: Call the function “factorial(n)”
Step 4: End

Factorial Function:
factorial(n):
if (n==0):
return 1
else:
return n*factorial(n-1)

1.5.3 Advantages of Recursive Functions:


 Recursion can produce simpler, more natural solutions to a problem
 It is written with less number of statements
 Recursive functions are effective where the terms are generated successively to
compute a value
 It requires few variables which makes program clean

PPG INSTITUTE OF TECHNOLOGY Page 20


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

 It is useful for branching processes

1.5.4 Difference between recursion and iteration


Recursion Iteration
Repetition is achieved through repeated Iteration is explicitly a repetition structure
function calls
Recursion terminates when a base case is Iteration terminates when the loop
recognized continuation test become false
Recursion causes another copy of the Iteration normally occurs within a loop, so
function and hence a considerable memory the extra memory assignment is omitted
space is occupied.

Example algorithm for Iteration Process


 Factorial of a given number
 Reverse of a number
 Fibonacci series
 Sum of digits
 Armstrong Number

Example algorithm for recursion


 Factorial of a given number using recursion
 GCD using recursion
 Tower of Hanoi using recursion

1.6 ILLUSTRATIVE PROBLEMS


1.6.1 MINIMUM IN A LIST
Problem
Finding the minimum element in the given list
Algorithm
STEP 1: Start
STEP 2: Read the numbers in the list Li
STEP 3: Assign min=L1

PPG INSTITUTE OF TECHNOLOGY Page 21


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

STEP 4: For each element Li in the list, do the following


If min>Li then
min=Li
STEP 5: Repeat the above step until the last element
STEP 6: Print min as minimum value
STEP 7: Stop

Flowchart
Start

Read the numbers in the list Li

min=L1

For each element in the list Li

F If
min>Li

min=Li

PPG INSTITUTE OF TECHNOLOGY Page 22


Print min
Stop

UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Pseudocode
READ the numbers in the list Li
ASSIGN min=L1
FOr each element Li in the list, do the following
IF min>Li THEN
min=Li
REPEAT the above step until the last element
PRINT min as minimum value

Program
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))

Output:
-8

PPG INSTITUTE OF TECHNOLOGY Page 23


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

1.6.2 INSERT A CARD IN A LIST OF SORTED CARDS


Playing cards:
Playing a card is one of the techniques of sorting and in Insertion Sort we follow
following steps.
– Start with an empty left hand and cards face down on the table.
– Then remove one card at a time from the table and Insert it into the correct position in
the left hand.
– To find a correct position for a card, we compare it with each of the cards already in
the hand from right to left.

Algorithm
STEP 1: Start
STEP 2: Read the list of ‘n’ sorted cards L
STEP 3: Get a new card
STEP 4: If new card is a number then
Compare the numbers in the list and place in the right order.
Else if new card is a role then
Compare Jack, Queen and King order and place in the right order.
STEP 5: Stop

Flowchart

Start

Read the list of ‘n’ sorted cards

Get a new card

T If new card is a number


PPG INSTITUTE OF TECHNOLOGY Page 24 F
Compare the numbers in the Compare Jack, Queen and King
list and place in the right order order and place in the right order
UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Stop

Pseudocode
READ the list of ‘n’ sorted cards L
GET a new card
IF new card is a number THEN
COMPARE the numbers in the list and place in the right order
ELSE IF new card is a role THEN
COMPARE Jack, Queen and King order and place in the right order.

1.6.3 GUESS AN INTEGER NUMBER IN RANGE


Problem
Guessing game - guessing a number within a range of numbers.
This task allows a player to guess a number that lies between 1 and L. The code
should repeat until the player guesses the correct number.

Algorithm
Step 1: Start
Step 2: Read the limit L
Step 3: Generate a Random number (r) between 1 and L
Step 4: Guess an integer number n between 1 and L.
Step 5: If n==r then

PPG INSTITUTE OF TECHNOLOGY Page 25


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Print “Number is Correct”


Else if n<r then
Print “Number is low”
Else
Print “Number is high”
Step 6: Repeat from step 3 if n!=r
Step 7: Stop.

Flowchart

Start

Read the Limit L

Generate Random number r between 1 and L

Read an integer number n between 1 and L

T F
If n==r

T F
If n<r

PPG INSTITUTE OF TECHNOLOGY Page 26


Print “Number is Correct” Print “Number is low” Print “Number is high”
UNIT I /Algorithmic
Stop
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Pseudocode
READ the limit L
GENERATE a Random number (r) between 1 and L
GUESS an integer number n between 1 and L.
IF n==r THEN
PRINT “Number is Correct”
ELSE IF n<r THEN
PRINT “Number is low”
ELSE
PRINT “Number is high”
REPEAT from step 3 IF n!=r

Program
import random
number = random.randint( 1, 100 )
print ('I\'m thinking of a number between 1 and 100')
print ('What is the number I\'m thinking of?')
attempts = 0
while answer != number:
attempts = attempts + 1
answer = input( 'Attempt ' )
answer = int( answer )
if answer > number :
print ('Lower')

PPG INSTITUTE OF TECHNOLOGY Page 27


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

elif answer < number :


print ('Higher')
elif answer == number :
print ('You got it in %i tries!' % (attempts))
print('the number is', number)

1.6.4 TOWERS OF HANOI


Problem:
 Tower of Hanoi is a mathematical puzzle with three rods and ‘n’ number of disks.
 These disks are in different sizes and stacked upon in an ascending order,i.e the
smaller one sits over the larger one.
 The objective is to move all the disks to some another tower without violating the
sequence of arrangement.
Rules to be followed:
 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.

Procedure:
If we have 2 disks then
 Move smaller disk to Auxiliary
 Move larger disk to destination
 Finally, we move disk from Auxiliary to destination

PPG INSTITUTE OF TECHNOLOGY Page 28


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Algorithm:
Main Program:
Step 1: Start
Step 2:Get the number of disc n
Step 6: Call the function Hanoi(n,a,c,b)
Step 7: Stop

Algorithm for Function Hanoi(n,src,dest,aux):


Step 1: if n=1 then
Move disk from source to destination
Else
Hanoi(n-1,src,aux,dest)
Move disk from src to dest
Hanoi(n-1,aux,dest,src)
End If
Step 2: Return to Main

Flow chart for Main:

PPG INSTITUTE OF TECHNOLOGY Page 29


UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Start

Read the number of disks ‘n’

Call Hanoi(n,src,dest,aux)
F

Stop

Flow chart for Hanoi Function:

If n==1 F

Move disk from src to destn Call Hanoi(n-1,src,aux,dest) F

Move disk from src to destn


PPG INSTITUTE OF TECHNOLOGY Page 30
Return to mainUNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving

Program:
class Tower:
def _init_(self):
self.counter = 0
def Hanoi(self,n,a,c,b):
if n==1 :
self.counter += 1
print (‘{0}->{1}’.format(a,b))
else:
self.hanoi(n-1, a,b,c)
self.hanoi(1, a,c,b)
self.hanoi(n-1, b,c,a)
def main():
tower = Tower()
tower.hanoi(3,”a”,”c”,”b”)

PPG INSTITUTE OF TECHNOLOGY Page 31

You might also like