python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING 9

Fundamentals of Computing – Identification of Computational Problems -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.

I. FUNDAMENTALS OF COMPUTING:

A computer is an electronic device that can be programmed to accept data (input), process it and
generate result. A computer along with additional hardware and software together is called a computer
system.

Data: Data is defined as an un-processed collection of raw facts, suitable for communication,
interpretation or processing
Information: Information is a collection of facts that is processed to give meaningful, ordered or
structured information.

Characteristics of Computer:
 Speed
 Diligent
 Accuracy
 Reliability
 Storage capability
 Resource Sharing
 Resource Sharing

1.1 Generations of Computer:

S.No Generation Period Component Features


1 First 1940-1956 Vaccum Tube Very Large
Consumed more power
Malfunction due to overheat
Machine language was used

2 Second 1956-1963 Transistor Smaller compared to first


Generate less heat
Consumed less power compared to first
Punched cards were used
Operating was introduced
Machine language and assembly
language were used

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


3 Third 1964-1971 Computers were smaller, faster and
reliable
Consumed less power
High level languages were used
Integrated Circuits

4 Fourth 1971-till date Micro Processors Smaller and Faster


Microcomputer series were developed
Portable computers were introduced

5 Fifth Present and Robot Artificial Intelligence is introduced


beyond Parallel and distributed computing
Development of robotics
Natural Language Processing
Voice recognition Software

1.2 Components of a Computer:

There are 3 main components:


1. Input/output system
2. Central Processing Unit(CPU)
3. Memory Unit

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


1. Input/Output Unit:
Input Unit:
- It accepts the data from the user
- It converts the data into a form that is understandable by the computer
- The input is given to the computer through the devices like keyboard, mouse, touch screen etc..

Output Unit:
- It provides the processed data (information) to the user,
- It is understandable by the user
- Some output devices are monitor, printer and speaker.

2. Central Processing Unit : (CPU)


- CPU or the processor is often called as the brain of the computer
- It controls, coordinates and supervises the operations of the computer
- It consists of
(i). Arithmetic and Logic Unit (ALU)
(ii). Control Unit (CU)
(iii). Set of registers

(i). Arithmetic and Logic Unit:


 ALU consists of 2 units. They are arithmetic unit and logic unit.
 The Arithmetic unit performs arithmetic operations on the data like addition, subtraction,
multiplication and division.
 The logic unit performs logic operations like comparing and testing.

(ii). Registers
 Registers are high speed storage area within CPU
 Registers store data, instructions, addresses and intermediate results of processing. So, registers
are often called as CPU’s working memory.
 The data and instructions that require processing must be brought in the registers of CPU before
they can be processed.
 Some of the important registers are
ACC : Accumulator stores the result of arithmetic and logical operations
IR : Instruction register contains the current instruction most recently fetched
PC : Program counter contains the address of next instruction to be executed
MAR : Memory Address register
MBR : Memory Buffer register
DR : Data Register

(iii). Control Unit(CU)


 The control unit organizes the processing of data and instructions.
 It acts as a supervisor, controls and coordinates the activity of the other units of computer

1. Memory Unit:
Cache Memory:
3

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


 Cache memory is placed between RAM and CPU.
 Frequently used instructions are stored in it.
 It is very fast , expensive and smaller.

Primary Memory:
Primary memory is the main memory of computer. It is used to store data and instructions during the
processing.
It is of 2 kinds: RAM and ROM
RAM:
 RAM is volatile
 It stores data when computer is on, so it is a temporary storage
 It provides limited storage capacity due to its high cost
ROM:
 ROM is non-volatile and read only memory.
 It is a permanent storage
 It comes programmed by the manufacturer.

Secondary Memory:
 The secondary memory stores data and instructions permanently.
 It is non-volatile memory
 Examples: Hard disk drive, floppy drive and optical disk drive
 It takes longer time to access data. It has high storage capacity
 It is cheaper than RAM

Applications:
 Science
 Education
 Medical and Health Care
 Engineering/Architecture/Manufacturing
 Entertainment
 Communication
 Business Application
 Publishing
 Banking

II. IDENTIFICATION OF COMPUTATIONAL PROBLEMS:

 Computational problem identification consists of 2 steps

1. Identifying and acknowledging that there is a problem


2. Developing a problem identification statement
 We need to four steps related to the identification of problem and its solutions. They are
decomposition, pattern recognition, abstraction, and algorithm design.

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Decomposition:

The first step of computational thinking is decomposition. This stage stars by analyzing the problem,
stating it precisely, and establishing the criteria for the solution.
A computational thinking approach to a solution often starts by breaking the problem down into smaller
more familiar components so they can managed easier. The more you can break a problem down, the
easier it to be solve.

Pattern recognition:

 Similarities and trends are identified within the problem.


 If some problems are similar in nature, there is a good chance that they can be solved using similar or
repeated techniques.
 This is a key component for making efficient solutions, and saving time in effective solutions to given
problems.

Abstraction:

 The abstraction stage involves the identification of key components of the solution
 It requires the ability to filter out unnecessary elements of a problem so that only focus on the important
elements.

Algorithm Design:

The final stage within the computational thinking process is algorithm design whereby a detailed step by
step set of instructions are created which explain how to solve the problems

III. ALGORITHMS:
 Algorithm is a step by step procedure for solving problem
 It is an ordered sequence of finite and well defined instructions for completing a task
 It is independent of any programming language.

Qualities of a good algorithm

Time – To execute a program, the computer system takes some amount of time. The lesser is the time
required, the better is the algorithm.

Memory – To execute a program, computer system takes some amount of memory space. The lesser is
the memory required, the better is the algorithm.

Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of
these may provide more accurate results than others, and such algorithms may be suitable.Properties of
Algorithm:

1. Finiteness: The algorithm should be terminated after a finite number of steps.


2. Definiteness: Each instruction must be clear, well-defined and precise.
3. Effectiveness: Each instruction must be carried out in specific amount of time.
4. Input: An algorithm have zero or more inputs
5. Output: An algorithm has one or more outputs

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Guidelines to write Algorithms:
 An algorithm should be clear, precise and well defined
 It should always begin with the word ‘Start’ and end with the word ‘Stop’
 Each step should be in a separate line
 Steps should be numbered as Step 1, Step 2 and so on.
Examples:
Algorithm 1 Write an algorithm to accept two numbers. Compare sum and print the result.
Step 1: Start
Step 2: Read two numbers A and B from user.
Step 3: Assign Sum = 0.
Step 4: Calculate Sum = A + B.
Step 5: Print Sum.
Step 6: Stop.

Algorithm 2 Algorithm to find the greatest among three numbers.


Step 1: Start
Step 2: Read three numbers A, B and C.
Step 3: Compare A and B. If A is the greatest perform step 4 else perform step 5.
Step 4: Compare A and C. If A is the greatest, output “A is the greatest” else output “C is the greatest”
Step 5: Compare B and C. If B is the greatest, output “B is the greatest” else output “C is the greatest”
Step 6: Stop.

Algorithm 3 Write an algorithm to find the minimum number in a given list of numbers.
Step 1: Start
Step 2: Read n.
Step 3: Read all n elements and store in list A.
Step 4: Assume first element in the list as min.
Step 5: Read all elements in the list one by one
If A[i] < min then assign
Min = a[i]
Step 6: Repeat step 5 till all the elements are compared.
Step 7: Print min as minimum element.
Step 8: Stop.

IV.BUILDING BLOCKS OF AN ALGORITHM

Algorithm can be constructed from basic building blocks


1. Statements
2. State
3. Control Flow and
4. Functions
1. Statements/Instructions:
 An algorithm is a sequence of instructions to solve a problem.
6

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


 An instruction describes an action. It should be in order.
 Algorithm consists of finite number of statements.
2. State:
 In an algorithm the state of a process can be represented by a set of variables. The state is simply
the value of the variables.
 As the values of the variables are changed, the state changes
 An algorithm starts from the initial state with some input values. As actions are performed, its
state changes and ends with a final state.
3. Control Flow:
 An algorithm is a sequence of statements .However, after executing a statement, the next
statement to be executed need not be the next statement in the algorithm.
 The statement to be executed next depends on the state of the process.
 This order of execution of statements is known as the control flow.
 There are 3 important control flow statements. They are
a. Sequence control flow
b. Selection control flow
c. Iteration control flow
a. Sequence control flow
A sequence of statements is executed one after another in the same order as they are written. All the
instructions execute only once.
Example Write an algorithm to accept two numbers. Compare sum and print the result.
Step 1: Start
Step 2: Read two numbers A and B from user.
Step 3: Assign Sum = 0.
Step 4: Calculate Sum = A + B.
Step 5: Print Sum.
Step 6: Stop.
b. Selection control flow
A condition of the state is tested and if the condition is true, one statement is executed, if the
condition is false an alternative statement is executed .
Example Algorithm to find the greatest among three numbers.
Step 1: Start
Step 2: Read three numbers A, B and C.
Step 3: Compare A and B. If A is the greatest perform step 4 else perform step 5.
Step 4: Compare A and C. If A is the greatest, output “A is the greatest” else output “C is the greatest”
Step 5: Compare B and C. If B is the greatest, output “B is the greatest” else output “C is the greatest”
Step 6: Stop.

c. Iteration (Looping) control flow


A set of statement are repetitively executed based upon a condition. If a condition evaluates to

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


true, the set of statements are executed again and again .As soon as the condition becomes false
the repetition stops.
Example Write an algorithm to find the minimum number in a given list of numbers.
Step 1: Start
Step 2: Read n.
Step 3: Read all n elements and store in list A.
Step 4: Assume first element in the list as min.
Step 5: Read all elements in the list one by one
If A[i] < min then assign
Min = a[i]
Step 6: Repeat step 5 till all the elements are compared.
Step 7: Print min as minimum element.
Step 8: Stop.

4. Functions:
 The complex problem will become simpler if the problem is broken into smaller called functions
and the smaller problems are solved.
 A function is a block of organized, reusable code that is used to perform a specific task.
 A function provides better modularity and high degree of reusability.

V. NOTATION:

A notation is system of characters, expression, graphics or symbols used in problem solving to


represent technical facts to facilitate the best result for a problem.
Example:
1. Pseudocode 2. Flowchart 3. Programing Languages.

1. PSEUDOCODE :
 Pseudo-imitation, Code- instruction
 Pseudocode is a short, readable and formally styled English language for explaining an algorithm.
 It is an outline of a program, written in a form that can be easily converted into realprogramming
statements
 Some keywords used are;
Input : INPUT, HET, READ AND PROMPT
Output : OUTPUT, PRINT, DISPLAY AND SHOW
Processing: COMPUTE, CALCULATE, DETERMINE, ADD, SUBTRACT, MULTIPLY AND
DIVIDE.
Initialize : SET and INITIALIZE
Incrementing: INCREMENT

Pseudocode Guidelines (RULES)

 Should be written in simple English.


 Only one statement per line
8

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


 Capitalize keywords, such as READ, PRINT, and so on
 Each set of instructions is written from top to bottom, with only one entryand one exit.
 It should allow for easy transition from design to coding in programminglanguage.

Benefits of pseudocode

 Language independent.
 It is easier to develop a program from a pseudocode than with a flowchart.
 It is easy to translate pseudocode into a programming language.
 It is compact and does not tend to run over many pages
 . Its simple structureand readability make it easier to modify.
Limitations of pseudocode
 It does not provide visual representation of the program’s logic
 Programmers use their own style of writing. There are no accepted standards.
 It cannot be compiled nor executed
Example: Find the product of any 2 numbers
READ values of A and B
COMPUTE C by multiplying A and B
PRINT the result C

2. FLOW CHART
 A flowchart is a pictorial representation of an algorithm
 A flowchart is drawn using boxes of different shapes with the lines connecting them to show the
flow of control.
 Boxes represent operations and the arrows represent the sequence.

Flowchart Symbols

Advantages of using Flowcharts:

1. Communication : Flowcharts are better way of communicating the logic of a system .


9

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


2. Effective analysis : Problem can be analyzed in more effectiveway.
3. Proper documentation: It serves as a good program documentation,which is needed for
various purposes.
4. Efficient Coding : The flowcharts act as a guide or blueprint during the systems analysis
program development phase.
5. Proper Debugging : The flowchart helps in debugging process.
6. 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.

Limitations of using Flowcharts:


1. Complex logic: Sometimes, the program logic is quite complicated.
2. Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.

Examples:

Flow chart 1: To multiply two numbers

Flow chart 2: To find the greatest among three numbers

10

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


3. PROGRAMMING LANGUAGES:

Computer programming languages are used to communicate instructions to the computer. They
are based on certain syntactic and semantic rules, which define the meaning of each of the
programming language construct.

They are divided into following categories:


1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming languages
6. Markup programming languages
7. Logic based programming languages
8. Concurrent programming languages
9. Object oriented programming languages

1. Interpreted Programming Languages

 An interpreted language is a programming language for which most of its implementation


executes instructions directly.
 The interpreter executes programs directly, translating each statement into sequence of one or
more sub-routines.

Example: BASIC, LISP, PASCAL, PERL, PYTHON

2. . Functional Programming Languages

11

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


 Functional programming language defines every computation as a mathematicalevaluation.
 Many of the functional programming languages are bound to mathematical calculation.

Example: CLEAN, CURRY, F#


3. Compiled Programming Languages

Compiled language is a programming language whose implementations are typically compilers and
not interpreters.

Example: C, C++, JAVA, VISUAL BASIC

4. Procedural Programming Languages

 Procedural (Imperative) programming language implies specified in the steps that the programs
should take to reach to an intended state.
 It makes the programs structured and easily traceable for program flow.

Example: MATLAB, HYPER TALK, MODULA-2

5. Scripting Programming Languages

Scripting programming language are programming languages that control an application.


Script can execute independent of any other application.
Example: PHP, VBSCRIPT, APPLE SCRIPT, WINDOWS POWERSHELL

6. Markup Programming Languages

A markup language is an artificial language that uses annotations to text that define how the text is to
be displayed.

Example: SGML, HTML, XML, XHTML

7. Logic Based Programming Languages

 Logic programming is a type of programming paradigm which is largely based on formal logic.
 Any program written in logical programming language is a set of sentences in logical form,
expressing facts and rules about some problem domain.

Example: ALF, Fril, prolog.

8. Concurrent Programming Languages

 Concurrent programming is a computer programming technique that provides for the execution of
operations concurrently, either within a single computer, or across a number of systems.
 In the later case, the term distributed computing is used.

Example: ABCL, CONCURRENT PASCAL

9. Object Oriented Programming Languages

12

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Object oriented programming language is a programming paradigm based on the concept of “objects”,
which may contain data, in the form of fields, often known as attributes and code, in the form of
procedures, often known as methods.

Example: AGORA, BETA, LAVA, MOTO.

VI. ALGORITHMIC PROGRAMMING SOLVING:


INTRODUCTION
Algorithmic problem solving is about the formulation and finding solution to problems..

1. UNDERSTANDING THE PROBLEM


 Understanding the given problem is very important before solving the problem.
 Understand the problem and clarify the doubts before going into next stage.
 Correct algorithm should work for all possible inputs.
 In this stage analyze what are all the inputs, required data, analyze who is going to usethis system
and what is the desired output.
2. ASCERTAINING THE CAPABILITIES OF A COMPUTATIONAL DEVICE
 The second step is to find out the capabilities of a machine.
 The instructions are executed one after another, one operation at a time,
 Depending on the capability of machine, algorithm is classified as
(i) Sequential algorithm
(ii) Parallel algorithm
CHOOSING BETWEEN EXACT AND APPROXIMATE PROBLEM SOLVING
The next decision is to choose between solving the problem exactly or solving it approximately. Based
13

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


on this, the algorithms are classified as exact and approximation algorithms. There are three issues to
choose an approximation algorithm.
1. There are certain problems like extracting square roots, solving non-linear equations which
cannot be solved exactly.
2. If the problem is complicated, it slows the operations. E.g. traveling salesman problem.
3. This algorithm can be a part of a more sophisticated algorithm that solves a problem
exactly.
DECIDING ON DATA STRUCTURES
Data structures play a vital role in designing and analyzing the algorithms. Some of the algorithm
design techniques also depend on the structuring data specifying a problem's instance.
Algorithm + Data structure = Programs
3. . ALGORITHM DESIGN TECHNIQUES
An algorithm design technique is a general approach to solving problems algorithmically that is
applicable to a variety of problems from different areas of computing. Learning these techniques is
important for two reasons.
1. They provide guidance for designing for new problems.
2. Algorithms are the cornerstones of computer science.
Algorithm design techniques make it possible to classify algorithms according to an underlying
design idea; therefore, they can serve as a natural way to both categorize and study algorithms.
METHODS OF SPECIFYING AN ALGORITHM
 Flowcharts and pseudo code are used for specifying an algorithm.
 Flowchart is a pictorial representation of algorithm.
 A Pseudocode, which is a mixture of a natural language and programming language like
constructs.

4. PROVING AN ALGORITHM'S CORRECTNESS


 Correctness has to be proved for every algorithm.
 To prove that the algorithm gives the required result for every legitimate input in a
finite amount of time.
 A technique used for proving correctness by mathematical induction because an algorithm’s
iterations provide a natural sequence of steps needed for such proofs.
5. ANALYSING AN ALGORITHM
There are two kinds of algorithm efficiency: time and space efficiency. Time efficiency
indicates how fast the algorithm runs; space efficiency indicates how much extra memory the algorithm
needs. Another desirable characteristic is simplicity. Simper algorithms are easier to understand and
program, the resulting programs will be easier to debug.
14

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


6. CODING AN ALGORITHM
 Programming the algorithm by using some programming language.
 Validity is done through testing and debugging.
 Inputs should fall within a range and hence require no verification. The analysis has tobe done in
various sets of inputs.
 A good algorithm is a result of repeated effort and work.
 The program's stopping or terminating condition has to be set.
 Another important issue is the question of whether or not every problem can be solved by an
algorithm.
 And the last, is to avoid the ambiguity which arises for a complicated algorithm.

VII. SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS

There are various kinds of algorithm development techniques formulated and used for different types of
problems.
1. Iteration 2. Recursion

1. ITERATION:

Iteration is a process of repeating the same set of statements again and again until the specified condition
holds true. Computers execute the same set of statements again and again by putting them in a loop.

In general, loops are classified as:


(i) . Counter-controlled loops
(ii). Condition -controlled loops

(i) Count-Controlled Loops

The number of iterations to be performed is known in advance. The counter-controlled loop starts with
the initial value of the loop counter and terminates when the final value of the loop counter is reached.
Since the counter-controlled loops iterate a fixed number of times, which is known in advance, they are
also known as definite repetition loops.
Example: Consider a program segment to find the sum of first 100 integers.
i =1
sum = 0
while (i<=100):
sum = sum + i
i=i+1

(ii)Condition-Controlled Loops
The number of times the iteration is to be performed is not known. The termination depends on the
special value in the condition. If the condition value is true, the loop body will be executed, otherwise
it will not. This is indefinite repetition loop.
Example: Consider a program segment to find the sum of first 100 integers.
1. Start
2. Read N
3. Assign sum = 0, i = 0
15

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


4. Calculate i = i + 1
5. Check whether i>=N, if not repeat step 4.Otherwise go to next step.
6. Print the value of sum
7. Stop

2. RECURSION:

In a recursive programming, a function calls itself. Recursion is used to solve the problems that can be
expressed in terms of similar problems of smaller size.
Direct Recursion:
A function is directly recursive if it calls itself.
Indirect recursion:
Indirect recursion occurs if the function calls another function.

Example: Recursive algorithm for finding the factorial of a number


1. Start
2. Read number n
3. Call factorial(n)
4. Print factorial f
5. Stop

VIII. ILLUSTRATIVE PROBLEMS


1. Find minimum in a list
2. Insert a card in a list of sorted cards
3. Guess an integer number in a range
4. Towers of Hanoi.

1. FIND MINIMUM IN A LIST

Problem statement:
Finding the minimum number in a list
16

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Algorithm:
1. Start
2. Assign the first value of the list as minimum value.
3. Compare this value to the other value starting from second value.
4. When a value is smaller than the present, then it becomes the new minimum.
5. Print the minimum value.

Flow Chart:
Start

Read n, List A

Min=A[0]

for i=1 to n-1

No
iF A[i]<Min

yes
Min=A[i]

PrintMMin

Stop

Pseudocode:
Min = A[0]
i=1
WHILE (i < = n-1)
IF(A[i] < MIN) THEN
Min = A[i]
END IF
i=i+1
END WHILE
PRINT Min

2. INSERT A CARD IN A LIST OF SORTED CARDS

Problem Statement:
17

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Imagine that you are playing a card game. You are holding the cards in your hand and these cards are
sorted. You are given one new card. You have to put into the correct place so that the cards you are
holding are still sorted.

Algorithm:
Step 1: Start
Step 2: Read all numbers in an array A.
Step 3: Read Key.
Step 4: From the first position to the end of the array compare key and array element.
Step 5: if key < A then assign i to pos, and return pos.
Step 6: from n-1 to pos move the elements one position down.
Step 7: Now store key value in pos location.
Step 8: Stop

Flowchart:

Start

Read A[], key

for i=0;i<=n-1;i++

No
Yes
if key<A[i]

pos=i

for (i=n-1;i>=pos;i--)

A[i+1]=A[i]

A[pos]=key

Print array A

Stop

Pseudocode:

Void inserting _ card( int A[], int n, int key)

18

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


{
int pos;
for(i = 0;i< = n-1:i + +)
{
If(key < A[i])
{
Pos = i;
return pos;
break;
}
}
for (i= n-1;i>=pos;i++)
{
A[i+1]=a[i];
}
A[pos]=key;
}

3. GUESSING AN INTEGER NUMBER IN A RANGE:

Problem Statement:

The objective is to randomly generate integer number from 0 to n. Then the player has to guess the
number. If the player guesses the number correctly output an appropriate message.

If the guessed number is less than the random number generated, output the message “Your guess
is lower than the number. Guess again” .Then the player guesses another number. This process is
repeated until the player guesses the correct number.

Algorithm:
1. Start
2. Generate a random number and read num.
a. Enter the number to guess.
b. If(guess is equal to num)
Print “You guess the correct number”
Otherwise
If guess is less than num0
Print “Your guess is lower than the number. Guess again”
3. Stop

Flowchart:

Start
19

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Read num

Read guess number

<num >num
if guess

=num

Your guess is you guessed the your guess is


lower than the correct number higher than the
number. Guess number. Guess
again again

Stop

Pseudocode:
Binsearch( int value)
{
int upperBound, lowerBound, mid;
upperBound = n - 1;
lowerBound = 0;
while ( lowerBound < = upperBound)
{
mid = (upperBound + lowerBound) / 2;
If(A[mid] = = value)
return mid;
else
if(value < A[mid])
upperBound = mid - 1;
else
lowerBound = mid + 1;
}
return;
}
4. TOWER OF HANOI PROBLEM:

Problem Statement:
20

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Tower of Hanoi is one of the classical problems of computer science. The problem states that,
1. There are stands(Stand 1,2 and 3) on which a set of disks, each with a different diameter, are
placed)
2. Initially, the disks are stacked on stand 1, in order of size, with the largest disk at the bottom.
The initial structure of Tower of Hanoi with three disks is shown below.

The “Tower of Hanoi problem” is to find a sequence of disk moves so that all the disks moved from
Stand-1 to Stand-3, adhering to the following rules.

1. Move only one disk at a time.


2. A largest disk cannot be placed on top of a smaller disk.
3. All disks except the one being moved be should be on a stand.

The general strategy for solving the Tower of Hanoi problem with n disks is shown below.

21

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


The movement of n-1 disks forms the recursive case of a recursive solution to move a disks. The base
case of a solution involves the movement of only one disk. The recurrence relation for solving the tower
of Hanoi problem can be written as:

Tower of Hanoi(disks) = { move the disk if disks = 1


Tower of Hanoi(disks-1) if disks > 1

Flowchart:

Hanoi

No
If disk=1
yes

Print move disk 1 from source to dest

Call function Hanoi with disk-1 , source , aux , dest

Print move disk n from source to dest

Call function Hanoi with disk-1 , aux , dest , source

Stop

22

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC


Recursive Algorithm:
Hanoi(disk, source, dest, aux)
1. If only one disk is there then move disk from source to dest
2. If more than one disk is there then
2.1 Recursively call Hanoi(disk-1,source, aux, dest)
2.2 Move disk from source to dest)
2.3 Recursively call Hanoi(disk-1,aux,dest,source)

Pseudocode:

START
Procedure Hanoi(disk, source, dest, aux)
If disk==1, THEN
Move disk from source to dest
ELSE
Hanoi(disk-1,source.aux,dest)
Move disk from source to dest
Hanoi(disk-1,aux,dest,source)
END IF
END Procedure
STOP

23

UNIT 1 PROBLEM SOLVING AND PYTHON PROGRAMMING AAMEC

You might also like