0% found this document useful (0 votes)
10 views

PSPP Unit I

python notes unit 1

Uploaded by

kavitha Mookkan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PSPP Unit I

python notes unit 1

Uploaded by

kavitha Mookkan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

[Type text]

Problem Solving and Python Programming


UNIT I

1.1 - ALGORITHMS
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm
is a well-defined computational procedure consists of a set of instructions that takes some values
as an input, then manipulate them by following prescribed texts in order to produce some values
as output.

INPUT ALGORITHM OUTPUT

1.1.1 –Two Phases of Algorithmic Problem Solving


• Derivation of an algorithm that solves the problem
• Conversion of an algorithm into code (or) program

1.1.2 –Data types and Data Structures:


In Algorithms the data are numbers, words, list & files. Algorithm provides the logic and
data provides the values.
Program = Algorithm + Data Structures
Data Structures refer to the types of data used and how the data are organized in the
program. The Programming languages provide simple data type such as Integers, real numbers
and characters.

1.1.3 – Characteristics of an Algorithm:


An algorithm should have the following characteristics.
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 input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.

Unit I Page 1.1


[Type text]

1.1.4 – Qualities of an Algorithm:


The following factors will determine the quality of an algorithm.
Accuracy Algorithm should provide accurate results.
Memory It should require minimum computer memory.
Time The time taken to execute any program is considered as a main quality.
Sequence The procedure of an algorithm must be in a sequential form.

1.1.5 – Representation of an Algorithm:


An algorithm can be represented in a number of ways which include
Natural Language usually verbose and ambiguous.
Flow Chart pictorial representation of an algorithm
Pseudo Code resembles common elements of an language and no particular format
Programming Language Algorithms are the basis of programs. Expressed in High level
language.

Examples:
1. Write an algorithm to find the area of circle.
Step1: Start
Step2: Read the value of radius as r
Step3: Calculate area = 3.14*r*r
Step4: Print the value of area.
Step5: Stop

2. Write an algorithm to find the biggest of two numbers.


Step1: Start
Step2: Read the value of a and b
Step3: Compare the value of a sand b if a>b then
Print ‘A is largest” otherwise print ‘b is largest’
Step4: Stop

3. Write an algorithm for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89.

Unit I Page 1.2


[Type text]

Step1: Start
Step2: Read Numbers as N
Step3: Initialize the value of Total as 0 and as 1
Step4: Repeat step 5 to step7 until i is less than n
Step5: Read the marks
Step6: Add mark to the total
Step7: Increment the value of i
Step6: Print the value of total
Step7: Stop

1.2 – Building Blocks of an Algorithm


There are four building blocks of algorithm which are
a) Instructions / Statement
i. Simple Statement
ii. Compound Statement
b) State
c) Control Flow
i. Sequence Control Structure
ii. Selection Control Structure
iii. Case Structure
d) Functions
a) Instructions / Statement
In Computer programming, a statement is a smallest standalone element which expresses
some action to be covered. It is an instruction written in a high level language that commands the
computer to perform a specified action. A program written in such language is formed by
sequence of one or more statements.
Ex:

An Algorithm to add two numbers:


Step-1: Start
Step-2: Declare variables num1, num2 and sum
Step-3: Read values num1, num2
Step-4: Add num1 and num2 and assign the result to sum

Unit I Page 1.3


[Type text]

sum num1+num2
Step-5: Display sum
Step-6: Stop
• There are two types of statements they are
i. Simple Statement
ii. Compound Statement
i) Simple Statement:
• Simple Statement consists of a single logical line.
Ex:
• Expression Statement
• Assignment Statement
• Print Statement
• Import Statement
ii) Compound Statement:
• Compound Statements consist of a group of statements. They control the execution of
other statements. It consists of one or more clauses.
Ex:
• if – statement
• while – statement
• for – statement
• try – statement
b) State
An algorithm is a deterministic automation for accomplishing a goal which given an
initial state, will terminate in a defined end state and internal state for performing an algorithm.
• Initial State starts by keyword “START” or “BEGIN”.
• Internal State starts from data, which is read as an input, written to an output and stored
for processing. The stored data is regarded as a part of Internal State.
• End State is nothing but the keyword “END”
c) Control Flow
Control Flow or Flow of Control is the order function calls, instructions and statement are
executed or evaluated when a program is running. Program Control structures are defined as the
program statements that specifies the order in which statements are executed. There are three
types of control structures. They are.

Unit I Page 1.4


[Type text]

i. Sequence Control Structure


ii. Selection Control Structure
iii. Case Structure

i) Sequence Control Structure


• Sequence Control Structure is used to perform the actions one after another. It performs
process A and then performs process B and so on. This structure is represented by writing
one process after another.
• The logic is from top to bottom approach.

Process 1 Start

Read radius r

Process 2 S=3.14*r*r

Print S

Process n
Stop

ii) Selection Control Structure


Selection Control Structure or Decision Control Structure allows the program to make a
choice between two alternate paths whether it is True or False.
1) IF….THEN
2) IF….THEN…ELSE
1) IF….THEN
• This choice makes between two processes.
o If the condition is true. It performs the process.
o If the condition is false. It skips over the process.

Pseudo code Flow Chart

IF Condition THEN

Unit I Page 1.5 IF


[Type text]

Process A



Process
END IF

2) IF….THEN…ELSE
• In this structure
o If the condition is true. It performs the process A.
o Else the condition is false. It executes process B.
• The process execution is depending on the condition.
Pseudo code Flow Chart
IF Condition THEN
Process A
ELSE IF

Process B Conditio
Process A ns
Process B
END IF

iii) Case Structure:


• This is a multi-way selection structures that is used to choose one option from many
options. If the value is equal to type 1 then it executes process-1, If the value is equal to
type 2 then it executes process-2 and so on. END CASE is used to indicate the end of the
CASE Structure.

Pseudo code Flow Chart


CASE TYPE
case Type-1:
Process 1 TYPE
case Type-2:

Unit I Page 1.6


[Type text]

Process 2


Process 1 Process 2 Process N

case Type-n:
Process n
END CASE

d) Functions
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data as INPUT, process it, and "return" a result as OUTPUT. Once a function is
written, it can be used over and over and over again. Functions can be "called" from the inside of
other functions. Functions "Encapsulate" a task (they combine many instructions into a single
line of code).
Ex:
>>>def add(num1,num2): #Function Definition
num3=num1+num2
print(“The sum is”,num3)
return num3
>>>a=10
>>>b=20
>>>c=add(a,b) #Function Call

Flow of a Function:
When a function is "called" the program "leaves" the current section of code and begins
to execute the first line inside the function. Thus the function "flow of control" is:
• The program comes to a line of code containing a "function call".
• The program enters the function (starts at the first line in the function code).
• All instructions inside of the function are executed from top to bottom.
• The program leaves the function and goes back to where it started from.
• Any data computed and RETURNED by the function is used in place of the function in
the original line of code.

Need for Functions

Unit I Page 1.7


[Type text]

• Functions allow us to create sub-steps. (Each sub-step can be its own function and a
group of Instructions)
• They allow us to reuse code instead of rewriting it.
• Functions allow us to keep our variable namespace without any confusion.
• Functions allow us to test small parts of our program in isolation from the rest.

The Steps to Write a Function


• Understand the purpose of the function.
• Define the data that comes into the function (in the form of parameters).
• Define what data variables are needed inside the function to accomplish its goal.
• Decide the data produces as output to accomplish this goal.

Parts of a "black box" (or) Parts of a function


Functions can be called "black boxes" because we don't know how they work. We just
know what is supposed to go into them, and what is supposed to come out of them.
1. The Name - describes the purpose of the function. Usually a verb or phrase, such
as "compute_Average", or just "average".
2. The Inputs - called parameters. Describe what data is necessary for the function
to work.
3. The Calculation - varies for each function
4. The Output – The calculated values from the function and "returned" via the
output variables.
Function Workspace
Every function has its own Workspace which means that every variable inside the
function is only usable during the execution of the function. After that we cannot use the
variable. The variables can be created inside the function or passed as an argument.

Function Workspace
Every function has its own Workspace which means that every variable inside the
function is only usable during the execution of the function. After that we cannot use the
variable. The variables can be created inside the function or passed as an argument.

Formal Parameters vs. Actual Parameters


• Inside the circle function, the variable ‘r’ will be used in place to calculate radius.

Unit I Page 1.8


[Type text]

• The parameter "r" is called a Formal parameter, this just means a place holder name for
radius.
The variable ‘radius’ is the Actual parameter, this means "what is actually used" for this call to
the function
Example:
Write a Python Program to find area of a circle:
>>>def circle(r): #Where ‘r’ is the Formal Parameter
rad=3.14*r*r
print(“The area of circle is”,rad)
>>>radius=9
>>>circle(radius) #Where ‘radius’ is the Actual Parameter

1.3 NOTATIONS (CLASSIFICATIONS OF AN ALGORITHM):


The Notations of an algorithm is classified into three
i. Pseudo code
ii. Flow Chart
iii. Programming Language

1.3.1. Pseudo Code:


• Pseudo code is a kind of structure English for designing algorithm.
• Pseudo code came from two words.
• Pseudo Means imitation
• Code means instruction
• Pseudo code is a text based tool for human understanding
• Pseudo cannot be compiled nor executed, and there are no real format or syntax rules
• The benefits of pseudo code is it enables the programmer to concentrate on the algorithm
without worrying about all syntactic details

Ex:
READ num1, num2
result = num1 + num2
WRITE result.

Basic Guidelines for writing Pseudo code:


• Write only one statement per line
• Each statement in your pseudocode should express just one action for the
computer
• Capitalize Initial Keyword

Unit I Page 1.9


[Type text]

• The keywords should be written in capital letters. Ex – READ, WRITE, IF,


ELSE, WHILE
• Indent to show hierarchy (order)
• We use a particular Indentation in each design.
• For sequence statement Indent start from same column
• For selection & looping statement Indent will leave some space and fall inside
the column.
• Ex:
IF a>b then
print a
ELSE
print b
• End multi line Structures
• Each structure must be ended properly to provide more clarity
• Ex: END IF
• Keep statements language Independent.
• The statement should be Independent to the language we are using. The
language features should be used properly.

Advantages of Pseudo Code.


• Can be done easily on a word processor.
• Easily modified.
• Implements structured concepts well.
• No special symbols are used.
• It is simple because it uses English like statements.

Disadvantage of pseudo Code.


• It is not visual.
• There is no standard format.
• Cannot be compiled not executed.

Examples:
1. Write a pseudocode to find the area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
COMPUTE Area=pi*r*r
PRINT r
2. Write a pseudocode to find the biggest of two numbers
BEGIN

Unit I Page 1.10


[Type text]

READ A, B
IF A>B
PRINT “B is big”
ELSE
PRINT “A is big”
3. Write a pseudocode for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89
BEGIN
INITIALIZE total=0,i=1
WHILE i<n
READ mark
total=total+mark
INCREMENT i
PRINT i
END

1.3.2. Flowchart
• A flow chart is a diagrammatic representation that illustrates the sequence of operations
to be performed to arrive the solution.
• Each step in the process is represented by a different symbol and has a short description
of the process steps.
• The flow chart symbols are linked together with arrows showing flow directions.

Flow Chart Symbols:

S.No Name of the Symbol Symbol Meaning

Represent the start and stop of


1. Terminal
the program

Denoted either an input or


2. Input / Output
output operation.

Unit I Page 1.11


[Type text]

Denotes the process to be


3. Process
carried out.

Represent decision making and


4. Decision
branching

Represent the sequence of steps


5. Flow Lines
and directions of flow
Represent a circle and a letter or
6. Connectors digit inside the circle. Used to
connect two flow charts

Types of Flow Chart:

• High Level Flow Chart:


• Shows major steps in the process.
• Which also includes intermediate outputs of each step.

• Detailed Flow Chart:


• Which provides detailed picture of a process by mapping all steps
• Which gives the detail about all the steps
• Deployment or Matrix Flow Chart:
• Which maps out the process in terms of who is doing the steps.
• Which is in the matrix format.
• Which shows various participants and the flow of steps among those participants.

Basic Guidelines for preparing Flow Chart:


• Flow chart should have all necessary requirements and should be listed out in logical
order.
• The Flow Chart should be clear neat and easy to follow. There should not be any
ambiguity.
• The usual direction of the flow chart is from left to right and top to bottom.
• Only one flow line should come out from a process symbol

Unit I Page 1.1 2


[Type text]

(or)

• Only one flow line should enter a decision symbol but two or three flow lines can leave.

• Only one flow line is used in conjunction with terminal symbol

Start Stop

• Write within standard symbols briefly. You can also use annotation symbol to describe
the data more clearly.
– – – Calculation Part

• If the flowchart becomes complex then it is better to use connector symbols to reduce the
number of flow lines.
• Flow chart should have a start and stop.
• Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
• Flow Charts are better in communication.
• A Problem can be analyzed in an effective way.
• Program Flow Charts Serve as a good documentation.
• Flow Charts acts as a blue print during system analysis and program development phase.
• The maintenance of operating program becomes easy with the help of flow chart.
Disadvantages of Flow Chart:
• Sometimes the program logic is quite complicated, In that case flowchart becomes
complex and clumsy.
• If alterations are required the flowchart may require re-drawing completely.
• As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Example:
1. Draw a flowchart to find the area of circle.

Unit I Page 1.13


[Type text]

Start

Read r

area=3.14*r*r

Print area

Stop

Start

Read a,b

2. Draw a flowchart to find the biggest of two numbers


If

a>b

print a is big print b is big

Unit I Page 1.14


[Type text]

yes No

Start

Read N

Total=0
i=1

If
i<n

3. Draw a flowchart for calculating total marks of specified number of subject

Print total Read Mark

Stop Total=Total+Mark

Unit I Page 1.15


[Type text]

Yes No

1.3.3 Programming Languages:


A computer is the ideal machine to execute computational algorithms because:
• A computer can perform arithmetic operations
• It can also perform operations only if it satisfies some condition.
A Programming language is a specialized language used to instruct the computer to solve
a particular problem.
Types of Computer Programming Languages

Unit I Page 1.16


[Type text]

There are three types of languages used in computer


i. Machine Language
ii. Assembly Language
iii. Programming Language
i) Machine Language
• Machine Language is also Known as Binary language or Low Level Language.
• Machine Language consists of 0’s and 1’s.
• Each Computer has its own machine language.
• The Machine Language encodes the instructions for the computer.
Ex:
01010010101

ii) Assembly Language


An Assembly language consists of English like mnemonics. There is one mnemonic for
each machine instructions of the computer.
An assembler is used to convert the assembly language into an executable machine code.
Ex for An Assembly language:
Start
add x,y
sub x,y


End

Difference between Pseudo Code and Assembly Language.

S.No Pseudo Code Assembly Language


Pseudo Codes are not compiled or Assembly Language should be compiled and
1.
executed. should be executed.
Pseudo Code should not have a Assembly Language should have a specified
2.
specified format. format known as mnemonics.

Unit I Page 1.17


[Type text]

iii) High Level Programming Language


• A High Level Programming Language consist of people language to simplify the
computer algorithms.
• A High Level Programming Language allows the programmer to write sentence in the
language which can be easily translated into machine language.
• The sentence written in High Level Programming Language is called as statements.
Ex for High Level Programming Language:
main()
{
if(x<y)
{
print(“x is greater”)
}
else
{
print(“y is greater”)
}
}

Some High Level Programming Language:


1. Fortan
2. C
3. C++
4. Java
5. Pearl
Define Compiler:
• A Compiler is a computer software that transforms computer code written in High Level
Programming Language into Machine Language (0,1) as well as vice versa.
Define Interpreter:
• An Interpreter translates a High Level Programming Language into an immediate form of
Machine Level Language. It executes instructions directly without compiling.
Define Assembler:

Unit I Page 1.18


[Type text]

• An Assembler is used to convert the Assembly Language into an executable Machine


Level Language.
Define Computer Program:
• A Computer Program is a combination of Computer algorithm and a Programming
language. Most programs are English like languages.
• A Computer Program will solve the problem specified in the algorithm.
1.4 Algorithmic Problem Solving:
A sequence of steps involved in designing and analyzing an algorithm is shown in the
figure below.

Understand the Problem

Decide on Computational Means,


exact vs approximate solving
algorithmic design technique

Design an algorithm

Prove Correctness

Analyze the algorithm

Code the algorithm


i) Understanding the Problem
• This is the first step in designing of algorithm.
• Read the problem’s description carefully to understand the problem statement
completely.
• Ask questions for clarifying the doubts about the problem.
• Identify the problem types and use existing algorithm to find solution.

Unit I Page 1.19


[Type text]

• An Input to an algorithm specifies an instance of the problem and range of the input to
handle the problem.
ii) Decision making
The Decision making is done on the following:
a) Ascertaining the Capabilities of the Computational Device
• After understanding the problem one need to ascertain the capabilities of the
computational device the algorithm is intended for.
• Sequential Algorithms:
o Instructions are executed one after another. Accordingly, algorithms designed to
be executed on such machines.
• Parallel Algorithms:
o An algorithm which can be executed a piece at a time on many different
processing device and combine together at the end to get the correct result.
iii) Choosing between Exact and Approximate Problem Solving:
• The next principal decision is to choose between solving the problem exactly (or) solving
it approximately.
• An algorithm used to solve the problem exactly and produce correct result is called an
exact algorithm.
• If the problem is so complex and not able to get exact solution, then we have to choose an
algorithm called an approximation algorithm. i.e., produces an approximate answer.
Ex: extracting square roots.
iv) Deciding an appropriate data structure:
• In Object oriented programming, data structures is an important part for designing and
analyzes of an algorithm.
• Data Structures can be defined as a particular scheme or structure to organize the data.

Algorithms+ Data Structures = Programs

v) Algorithm Design Techniques


• An algorithm design technique (or “strategy” or “paradigm”) is a general approach
to solve problems algorithmically that is applicable to a variety of problems from
different areas of computing.
• First they provide guidance for designing an algorithm.
• Second, they classify algorithm according to the design idea.

Unit I Page 1.20


[Type text]

vi) Methods of specifying an algorithm:


• Once an algorithm is designed, we need to specify it some way. There are three ways to
represent an algorithm.
o Pseudo code – is structured English.
o Flowchart – a pictorial representation of an algorithm.
o Programming Language – a high level language to instruct computer to do some
action.
vii) Proving an algorithm’s correctness:
• Once an algorithm has been specified, it has to be proved for its correctness.
• An algorithm has to prove with the input to yield a required output with respective of
time. A Common technique is mathematical induction.
viii) Analyze the algorithm:
• For an algorithm the most important is efficiency. In fact, there are two kinds of
algorithm efficiency. They are:
o Time efficiency, indicating how fast the algorithm runs, and
o Space efficiency, indicating how much extra memory it uses.
• The efficiency of an algorithm is determined by measuring both time efficiency and
space efficiency.
Some factors to analyze an algorithm are:
o Time efficiency of an algorithm
o Space efficiency of an algorithm
o Simplicity of an algorithm
o Generality of an algorithm
ix) Coding of an algorithm:
• The coding / implementation of an algorithm is done by a suitable programming language
like C, C++, JAVA, PYTHON.
• The transition from an algorithm to a program can be done correctly and it should be
checked by testing.
• After testing, the programs are executed and this solves our problem.

1.5 Simple Strategies for Developing Algorithms (Iteration, Recursion:


Iteration:

Unit I Page 1.21


[Type text]

An Iterative function is one that repeats some parts of the codes again and again until one
condition gets false.
Ex:
Write a Python program to print 10 values:
>>>i=0
>>>while i<=10:
print(“The Value of i is”,i)
i++
>>>

Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and the
particular function is called again and again.

Difference between Recursion and Iteration:


S.No Recursion Iteration
Recursion is achieved through
1. Iteration is explicitly a repetition structure.
repeated function calls.
Recursion terminates when a base case Iteration terminates when loop continuation test
2.
is recognized. becomes false.
Recursion causes a copy of function
Iteration normally occurs within a loop so extra
3. and additional memory space is
memory is omitted.
occupied.

Examples:
Algorithm, Pesudocode, Flowchart for finding Factorial using Recursion
1. Algorithm to find the factorial of given number using recursion
Step1: Start
Step2: Read the value of n
Step3: Call factorial(n) and store the result in f

Unit I Page 1.22


[Type text]

Step 4: Print the factorial f


Step5: Stop
Subprogram
Step1: Start factorial(n)
Step2: If n is equal to zero then return the value 1
else return n*factorial(n-1).
Sep 3: Stop factorial

2. Write the pseudocode for finding the factorial using recursion


BEGIN factorial
READ n
f=factorial(n)
PRINT f
subprogram
Begin Factorial (n)
IF n==0 THEN return 1
ELSE return n*factorial(n-1)
END

Factorial(n)
Start

Read n Return
3. Draw the flowchart for finding the factorial using reifcursion n*factorial(n-1)
n==
0
f =factorial(n)

Return 1
No
Print f
Unit I Page 1.23
[Type text]

yes

ILLUSTRATIVE EXAMPLES
1.1. Find Minimum in a list:
Algorithm: Start
Step1:Start
Step2:Read total number of elements in the list
Read N
Step3:Read the first element as E
Step4:MIN=E
Read first Element as E
Step5:SET i=2
Step6:If i>n goto Step 11 ELSE goto Step 7
Step7:Read ith element as E Min= E I=2

Step8:if E < MIN then set MIN=E


Step9:i=i+1
IS
Step10:goto Step 6
I<N
Step11:Print MIN
Step12:stop
Read I th Element as E
Pseudocode
BEGIN
READ total number of elements in the list Is
READ the first element as E E<
N
SET MIN=E
SET i=2
MIN=E
WHILE I <= n
Read ith element as E
if E < MIN then set MIN=E I=I+1

Unit I Page 1.24 Print MIN


[Type text]

i=i+1
Print MIN
END
Flow chart:

1.2. Find how to insert a card in a list of sorted cards:


Insterting a card in a list of sorted card is same as inserting an element into a sorted array.
Start from the high end of the list, check to see where we want to insert the data. If the element is
less than then move the high element one position and next check with next element repeat the
process until the correct position and then insert the element.

Unit I Page 1.25


[Type text]

Position 0 1 2 3 4 5
Original list 4 6 9 10 11
7>11 4 6 9 10 11
7>10 4 6 9 10 11
7>9 4 6 9 10 11
7>6 4 6 7 9 10 11

Algorithm: Start

Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element Rineasdonroteodf elilesm
t aenstN
as E
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1 i=0
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go it<oNstep 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1

Pseudocode Read Sorted List List[i]


READ Number of element in sorted list as N
SET i=0
WHILE i<N
READ Sorted list element as List[i] Read x
i=i+1 i=N-1
ENDWHILE
READ Element to be insert as X
SET i = N-1
WHILE i >=0 and X < List[i]
List[i+1] =List[i] i>=0
i=i–1 &&
END WHILE X<List[i
List[i+1] = X ]
Flow Chart

List[i+1]=List[i]
i=i+1

List[i+1]=X
Unit I Page 1.26
[Type text]

1.3. Find how to guess an integer number within a range:


The computer randomly selects an integer from 1 to N and ask you to guess it. The
computer will tell you if each guess is too high or too low. We have to guess the number by
making guesses until you find the number that the computer chose.
.
Algorithm

Unit I Page 1.27


[Type text]

Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Start
Step 5: READ User Guessed Number as G
Step 6: Count = Count +1 Count=0
Step 7: IF R==G THEN go to step 10 ELSE go to step 8
Step 8: IF R< G THEN PRINT “G
ReuaedssrainsgeTN
oo High” AND go to step 5 ELSE go to step9
Step 9: PRINT “Guess is Too Low” AND go to step 5
Step 10: PRINT Count as Number of Guesses Took
R=random Number from 1 to N

Pseudocode:
SET Count =0
READ Range as N Read User guessesed Number G

SELECT an RANDOM NUMBER from 1 to N as R


WHILE TRUE
Count=Count+1
READ User guessed Number as G
Count =Count +1
IF R== G THEN
IS
BREAK R==
ELSEIF R<G THEN G
DISPLAY “Guess is Too High”
ELSE
IS
DISPLAY “Guess is Too Low” R>G
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took
IS Print “Grade is high”

R>G

Print “Grade is too low”

Unit I Page 1.28 Print count


[Type text]

1.4 Find the towers of Hanoi:


The Tower of Hanoi puzzle was invented by the French mathematician it has three poles
and a stack of disks, each disk a little smaller than the one beneath it. Their assignment was to
transfer all the disks from one of the three poles to another.
• This should be done with two important constraints.
o We can only move one disk at a time.

Unit I Page 1.29


[Type text]

o We cannot place a larger disk on top of a smaller one.


Figure 1 shows an example of a configuration of disks in the middle of a move from the
first pole to the third pole.

An outline to
solve this
problem,
from the
starting pole,
to the goal
pole, using an intermediate pole:
1. Move a tower of height-1 to an intermediate pole, using the final pole.
2. Move the remaining disk to the final pole.
3. Move the tower of height-1 from the intermediate pole to the final pole using the
original pole.
we can use the three steps above recursively to solve the problem.

Unit I Page 1.30


[Type text]

Python Program to solve Towers of Hanoi:


>>>def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
>>>def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
>>>moveTower(3,"A","B","C")
Output:
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B

A recursive Step based algorithm for Tower of Hanoi


Step 1: BEGIN Hanoi(disk, source, dest, aux)
Step 2: IF disk == 1 THEN go to step 3 ELSE go to step 4
Step 3: move disk from source to dest AND go to step 8
Step 4: CALL Hanoi(disk - 1, source, aux, dest)
Step 5: move disk from source to dest
Step 6: CALL Hanoi(disk - 1, aux, dest, source)
Step 7: END Hanoi

A recursive Pseudocode for Tower of Hanoi


Procedure Hanoi(disk, source, dest, aux)
IF disk == 1 THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF

Unit I Page 1.31


[Type text]

END Procedure
Flow Chart for Tower of Hanoi Algorithm

Begin Hanoi(disk,source,dest,aux)

IS
disk==1

Honai(disk-1,source,aux,dest)
Move disk from source to dest

Move disk from source to dest

Honai(disk-1,source,aux,dest)

Stop

Unit I Page 1.40


[Type text]

Unit I Page 1.41


[Type text]
TWO MARKS

1. What is an algorithm? (University question)


Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for
completing a task. It is an English-like representation of the logic which is used to solve the
problem. It is a step- by-step procedure for solving a task or a problem. The steps must be
ordered, unambiguous and finite in number.

2. Write an algorithm to find minimum of 3 numbers in a list. (University question)


ALGORITHM : Find Minimum of 3 numbers in a list
• Step 1: Start
• Step 2: Read the three numbers A, B, C
• Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5 Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to step 6.
• Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
• Step 6: Stop

3. List the building blocks of an algorithm.


• Statements
• Sequence
• Selection or Conditional
• Repetition or Control flow
• Functions

4. Define statements. List its type


Statements are instructions in Python designed as components for algorithmic problem
solving. For example. An input statement collects a specific value from the user for a variable
within the program. An output statement writes a message or the value of a program variable to
the user’s screen.
5. Write the pseudo code to calculate the sum and product of two numbers and display.
BEGIN
INITIALIZE variables sum, product, number1, number2
READ number1, number2 sum = number1+ number2
PRINT “The sum is “, sum

Unit I Page 1.42


[Type text]

COMPUTE product = number1 * number2


PRINT “The Product is “, product
END
6. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data, process it, and "return" a result. Once a function is written, it can be used
over and over again. Functions can be "called" from the inside of other functions.

7. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
BEGIN
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
8. Give the rules for writing Pseudo codes.
o Write one statement per line.
o Capitalize initial keywords.
o Indent to show hierarchy.
o End multiline structure.
o Keep statements to be language independent
.
9. Give the difference between flowchart and pseudo code.
• Flowchart is a graphical representation of the algorithm.
• Pseudo code is a readable, formally English like language representation.
10. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart
is drawn using boxes of different shapes with lines connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.

11. Give an example of Iteration. a = 0

Unit I Page 1.43


[Type text]

for i from 1 to 3 // loop three times


{
a=a+I // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)

12. Write down the rules for preparing a flowchart.


• A flowchart should have a start and end,
• The direction of flow in a flowchart must be from top to bottom and left to right
• The relevant symbols must be used while drawing a flowchart.

13. Mention the characteristics of an algorithm.


• Algorithm should be precise and unambiguous.
• Instruction in an algorithm should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• Algorithm should be written in sequence.
• Algorithm should be written in normal English.
• Desired result should be obtained only after the algorithm terminates.

14. Define the two modes in Python.


Python has two basic modes: script and interactive.
The normal mode is the mode where the scripted and finished .py files are run in the Python
interpreter. Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory

15. Give the various data types in Python


Python has five standard data types
• Numbers
• String
• List
• Tuple
• Dictionary

Unit I Page 1.44


[Type text]
16. List out the simple steps to develop an algorithm.

Algorithm development process consists of five major steps.


• Step 1: Obtain a description of the problem.
• Step 2: Analyze the problem.
• Step 3: Develop a high-level algorithm.
• Step 4: Refine the algorithm by adding more detail.
• Step 5: Review the algorithm.

17.Give the differences between recursion and iteration


Recursion Iteration
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
Only base condition (terminating condition) is It involves four steps: initialization, condition,
specified. execution and updation.
It keeps our code short and simple. Iterative approach makes our code longer.
It is slower than iteration due to overhead of Iteration is faster.
maintaining stack.
It takes more memory than iteration due to Iteration takes less memory.
overhead of maintaining stack.

18. What are advantages and disadvantages of recursion?


Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.

A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.

Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.

Unit I Page 1.45


[Type text]
18. What are advantages and disadvantages of recursion?

Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.

A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.

Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.

19. Define control flow statement.


A program's control flow is the order in which the program's code executes. The controlflow
of a Python program is regulated by conditional statements, loops, and function calls.

20. Write an algorithm to accept two number. compute the sum and print the result.
(University question)

Step 1: Start
Step 2: READ the value of two numbers
Step 3:Compute sum of two numbers
Step 4 :Print the sum
Step 5:Stop
21. Write an algorithm to find the minimum number in a given list of numbers. (University
question)
• Step 1: Start
• Step 2:Read the total number of element in the list as N
• Step3:Read first element as E
• Step 4:MIN=E
• Step 5:Set i=2
• Step6:IF i>n goto Step 11 ELSE goto Step 7
• Step 7:Read i th element as E
• Step 8:IF E<MIN then set MIN=e
• Step 9:i=i+1
• Step 10:goto step 6
• Step 11:print MIN
Unit I Page 1.46
[Type text]
• Step12:Stop

22. Outline the logic to swap the contents of two identifiers without using the third variable
(University question)
• Step1: Start
• Step 2:Read A,B
• Step 3 :A=A+B
• Step 4:B=A-B
• Step5:A=A-B
• Step 6:Print A ,B
• Step 7:Stop

Unit I Page 1.47


[Type text]

Unit I Page 1.48

You might also like