PROBLEM SOLVING AND PYTHON
PROGRAMMING
UNIT-1
ALGORITHMIC PROBLEM SOLVING
PART-A
1. ALGORITHAM
Algorithm is defined as a step procedure for solving any problem it is
also
a previous rule specifying how to solve a problem
QUALITIES
Accuracy
Memory
Time
Sequence
2. What are characteristics of algorithm?
A algorithm has a first number of inputs
Every instruction should be preise
Ensure that algorithm has proper fernination
Effectness of each step is very important
The desired output must be obtrined only after the algorithm terminates
the algorithm should be written in sequence
3. Advantage and Disadvantages of flowchar?
ADVANTAGE
Communication
Effective Analysis
Proper documentation
Efficient winding
Proper debugging
Proper testing
Efficient program maintenance
DIS-ADVANDGES
Complex logic
Reproduction(or)Alteration
Unknown
cost
Modification
4. What are the step to followed to frame a function block?
Understand the purpose of the function
Define the data that come into the function from the caller
Define what data variable are need inside of the function to accomplish
to goal
Decide on the set to that the program will use to accomplish this goal
5. Advantages of Recursive function?
Recursion can produce simpler more natural solution to a problem
If is written which less number of statements
Recursion function are effective where the term are generated
successively to compute a value
It require few variable which make program clean
It is useful for branching process
6. Write pseudo code to find largest of two number ?
Set initialize AB
READ A B
IF A>B then
PRINT A is greates
ELSE
PRINT B is greates
END IF
STOP
7. What are the two of statement available in algorithm ?
Simple statement
Compound statement
SIMPLE STATEMENT
Assignment A:=A+5
goto: goto Next
return: return 5
call: function( )
COMPOUND STATEMENT
Block
Do loop
For loop
If statement
Else
Switch statement
Switch ( )
{
Case ‘a’;
Alert( );
Break;
Quit( )
Break;
}
While loop
Exec
Eval
8. Draw flowchart to find largest of two number?
START
Start
Read A, B
If
A>B
Print A Print B
Stop
9. How many type the algorithm can be represented?
Normal English
Program
Flowchart
Pseudo code
Decision cod
10. Define Iteration
In iteration the control statement such as for 100p ,do-while
loop(or)which is use the loop conlives its execution until the tesninating
condition is reached
11. Draw flowchart to find factorial of number?
Start
Initialize
R=1 Fact=1
Read the value of
n
If(i<=n)
Fact=fact*i i=i+1
Print fact
stop
PART –B
1. Building block of algorithm ?
INSTRUCTION:
In computer programming a statement is the smallest stand alone
element of an imperation programming language that express some
action to be carried out
KIND OF SATEMENTS
Simple statement
Compound statement
SIMPLE STATEMENT
Assignment A:=A+5
goto: goto Next
return: return 5
call: function( )
COMPOUND STATEMENT
Block
Do loop
For loop
If statement
Else_
While.loop :which(…..)do…
Switch statement:
Switch(c){ case ‘a’;alert( );break;case’q’;quit( );break;}.
This is found is the exes and eval function found in some language
In the python both and found with exes applied to statement and eval
applied to statement and eval applied to expression
STATE:
An algorithm is detesninstic auto naton for accomplishing a goal which,
given an iuitial state ,will tesninate in a define end state
CONTROL FLOW:
An algorithm referred to as flow of control, control flow is order
function call ,instruction and statement are executed when a program is
running
SEQUENCE CONTROL STRUCTURE:
As the name suggest the sequence control structure is used is to perform
the action out after anther it perform process A and then performs
process B and so on the logic flow is top to bottom approach
Flow chart start
PREUDO CODE
Process 1
Process 1 Read the
radius r
Process 2
Process 2
Process 3
S=A+B
Process 3
Print S
Stop
SELECTION CONTROL STRUCTURE
This is make a choice between two process
IF the condition is true if performs the process
IF the condition is false it skips over the process
Pseudo code:
If condition THEN
Process 1
..
..
End if
Flow chart:
If
condition
Process
IF……THEN ELSE STRUCTURE:
In this stricter if the condition is true is executes process 2
PSEUDO CODE
IF Condition then
Process 1
..
..
Else
..
..
Process 2
End if
Flow chart
If
condition
Process 1 Process 2
CASE STRUCTURE :
This is a multiways selection structure that is used to choose one option
from many options
Pseudo code:
Case type 1
Case type 1
Process 1
Case type 2
Process 2
..
..
Case type n
Process n
..
..
End if
Flow chart:
Type
Process 1 Process n
Process 2
FUNCTION:
Function are self contained modules of code that accomplish a specific
task , function useally take in data ,process it and return a result
SYNTAX:
Def(function name)( );
Body of the function( );
The program comes to a line of code complain a function call
All instruction inside of the function are executed from top bottom
The program levels the function angle goes back to where it started
from
Any data computed and returned by the function is used in please of the
function in the original line of code
2. What is pseudo code and explain the rules for writing pseudo code with
suitable example?
PSEUDO CODE:
Pseudo code came from two word pseudo and code ”pseudo” means
initiation and ”code” refer to instruction written in the programming
language pseudo code is programming analysis tool that is used for
planning program logic
EXAMPLE:
READ num1,num2
Result=num1+num2
WRITE result
BASIC GUIDELINE FOR WRITING PSEUDO CODE
i. WRITE ONLY ONE STATEMENT PER LINE
Each statement in your pseudo code should express first one action for
the computer you should write anther statement in next new line
EXAMPLE:
READ name m1,m2,m3
TOT=m1+m2+m3
Avg=tot/5
WRITE Tot,avg
ii. CAPITALIZE INITIAL KEYWORDS:
The keywords should be written in capital lettes
EXAMPLE:
IF, ELSE, ENDIF, WHILE, ENDWHILE
iii. INDENT TO SHOW HIERARCHY:
Indeutation is a process of showing the boundaries of the statement it is
used for read ability
EXAMPLE:
If a>b then
Print a
ELSE
Print b
iv. END MULTI LINE STRUCTURE:
Each structure must be ended properly which provides more clarity
EXAMPLE:
ENDIF for IF statement
v. VEEP STATEMENT LANGUAGE INDEPENTANT
Here language refer programming language our psudo code is not
dependent to the program coding
3. What are the variable guidestise to be followed while drawing a flow
chart? Draw flow chart to print largest among there number?
In drawing a proper flow chart, all necessary requirement should
be listed that in logic code
The flowchart should be clear, ueat and easy to follow there should
not be any room for ambiguity in understanding the flowchart
The usual direction of the flow of a procedure or system is from left
to right or top to bottom
Only one flow line should come out from a process symbol
Only one flow line should enter a direction symbol but two or three
flow line, one for each possible answer, cap leave the decision
symbol
Only one flow line is used in conjunction with terminal symbol
stop
start
Write within statement symbols briefly if necessary, you can use the
annotation symbol to describe data or computational
If the flowchart becomes complex,it is bettes to use connector symbol to
reduce the number of flow line . avoid the inter section of flow line if
you want to make it more effective and better way of communication
Ensure that the flow chart has a logical start and stop
Validity of the flowchart can be tested by passing through it with simple
test data
ADVANAGES OF FLOWCHART:
Communication
Effective analysis
Proper documentation
Proper debugging
Efficient coding
Efficient program maintenance
DIS-ADVANAGES OF FLOWCHART:
Complex logic
Modification or Pltesation
Reproduction
Unknown
Cost
TO PRINT LARGEST OF THREE NUMBERS:
start
Read A, B
If a>b and
a>c
Print A is great If b>c
Print A is great Print A is great
Stop
4. Function
Function are “self contained contained” moduler of code that
accomplish a specific task function usually “the in “ data process it and
“return” a result. once a function is written, in can be used over and
over again function can be”called” from the inside of other function
Function “Encapsulate” a task most programming language provide
many step to accomplish
When a function is called the program levess the current section of
code and begin to execute the first line inside the function
The program come to line of code containing a function call
The enter the function
All instruction inside of the function are execute from top to bottom
The program leaves the function and goes back to where it started from
STEP TO WRITING A FUNCTION:
Understand the purpose of the function
Define the data that come inter the function from the caller
Define what data variable are needed inside the function to accomplish
this goal
Decide on the set of step that the program will use to accomplish this
goal
PARTS OF FUNCTION:
Function can be called “block boxes”because we don't need to know
they work just what is supposed to go into them, and what is supposed
to come out of them.
when defining a program as a block box , we must described the
following attributes of the function
Formal vs actual:
When we create a function, it should represent a "genetic" action that
can be applied in many circumstaneous given any list of grades we can
compute an average.
but if it can be any list of grades, how do we know what the list of
grades will be called? the answer we don't care
when writing a function the programmer must provide a blank to plog in
what ever data is of current interest. The blank should have a good
symbolic name saging what it will represent
function average -grade ( list-of-grader)
..
..
end function
Inside the average-grade function, the name list-of-grader will be used
in place of what over variable some other user has stored his or her
grades in // this some others code (noy the function
code)
mid term-grades=...//create array of grader.
print"the average of the midterm was"
print average - grade (mid term-grader)
This during the excution of the program both names will refer to the
some thing but at different tuies
The parameter "list-of-grades "is called a formal parameter; again this
just means a place holds name for any possible set of grades.
The variable midterm- grades is the actual parameter: this means " what
is actually used" for this call to the function , such as [90,100,70];
5. Explain Algorithm problem solutions technique in details?
Algorithm are procedural solution to problems. These solutions are not
answers but specific instruction for getting answer.
a) Understanding the problems:
Before designing an algorithm you have to understand completely the
problem given
Read the problems description carefully and task questions it there are
any doubts and the problem do a few examples by hand, think about
special cases, and ask questions again i/needed.
An input to an algorithm specifies an instance of the problem the
algorithm solves. If is important to specify exactly the range of instances
the algorithm needs to handle.
b) Ascertaining the capabilities of the computational Device:
Over you completely Understand a problem, you need to as certain the
capabilities of the computational device the algorithm is intended for`
Sequential algorithm:
Instructions are executed are after another one operation at a time.
Accordingly algorithms designed to be executed on such machines.
Parallel algorithm:
The central assumption of the RHM model does not for some newer
computers that can execute operations concurrently, i.e. in parallel.
c) Choosing between Exact and Approximate problem solving:
The next principal decision is to choose how to slove the problem.
Solving the problem exactly is called an exact algorithm
Solving it approximatly is called in approximation algorithm
Why would one opt for au approximation algorithm?
First, there are important problems that simply cannot be solved exactly
for most of their instances; Examples, include evaluating definite
integrals
Second. available algorithm for solving a problem exactly can be
unacceptably slow because of the problem intrinsic complexity, This
happens, in particular for many problems involving a very large number
of choices.
Third, an approximation algorithm can be a part of more sophisticated
algorithm that solves a problem exactly.
d) Deciding an appropriate Data Structure:
In the new world for of object programming, data structures remain
crcrerally important for both design and analysis of algorithm Data
structures can be defined as a particular scheme of organizing related
data items
Algorithms+ Data structures= programs
e) Algorithm Design Techniques:
An algorithm design techniques is a general approach to solving
problems algorithmically that is applicable to a variety of problems
from different areas of computing
First, they provide quidance for designing algorithm`s job now problems
i.e, problems for which there is no known satisfactory algorithm.
Second, algorithm are the cornerstone of computes science. Every
science is interested in classfying its principle subject and computers
science no exception, algorithm design techniques makes it possible to
classifly algorithm according to an underlying design idea; therefore ,
they can serve as a natural way to both catgorize and study algorithms.
vi. Methods of Specifying an Algorithm:
Once an algorithm is designed, you need to specify it in some fashion
free and also a step by- step form
pseudo code
these are two options are most widely used nowadays specifying
algorithm
pseudo code is a mixture a natural language and programs language like
constructs. pseudo code is usually more precise than natural language,
and its usage often yields more succint algorithm descriptions
In there earlies days of computing the dominant vehicle for specifying
algorithm was a flowchart, a method of expressing an algorithm by a
collection of connected geometric shapes containing descriptions of the
algorithm`s steps. This representation technique use proved to be
inconvenient for all but very simple algorithm.
vii. Proving an algorithm`s correctness:
Once an algorithm has been specified, it has to be proved for its
correctness. That is, you to prove that the algorithm yields a required
result for every logitimate input in a finite amount of time.
A common technique for proving correctness is to use mathematical
induction because an algorithm`s iterations provide a natural sequence
of steps needed for proofs. Althrough tracing the algorithm`s
performance for a few specific input can be a very worthwhile activity it
cannot prove the algorithm`s correctness conclusively. But in order to
show that can algorithm is in correct you need just one instance of its
input for which the algorithm fails.
The notion of correctness for approximation algorithm is less straight for
ward than it is for exact algorithm. For an approximation algorithm. we
usually would like to be able to show that the error produce by the
algorithm does not exceed a prodefined limit.
viii. Analyzind an Algorithm:
Efficiency is an important characteristic of any algorithm
There are two kinds of algorithm efficiency
Time efficiency, indicating how just the algorithm runs
Space efficiency, indicating how much extra memory it uses
Another desriable characteristic of an algorithm is simplicity. Because
simpler algorithm are easier to understand and easier to program;
consequently, the resulting programs usually contains fewer buys,
sometimes simpler algorithms are also more efficient then more
complicated alternatives
yet another desirable characteristic of au algorithm is generality.
There are two issues here:
i. Generality of the problem the algorithm solves and
ii. The set of input is accepts
sometimes it is easies to design an algorithm for a problem posed in
more general terms. There are situation, hower, where designing a more
general algorithm is unnecessary or difficult or over impossible to the
set of inputs, the main concern should be designing an algorithm that
can handle a set of inputs that is natural for the problem at hand
It you are not satisfied with the algorithm`s efficiency, simplicit or
generality, you must return to the drawing board and redesign the
algorithm. In fact even if your evaluation is possible it is still worth
searching for other algorithmic solutions
i. Coding an algorithm;:
Most algorithm are destined to be ultimately implemented computer
programs, an algorithm presents both a perill and an opportunity, The
peril lies in the possibility of masking the transition from an algorithm to
a program either incorrectly or very inefficient some influential
computers scientists strongly belives that unless the correctness of a
computer program is proven with full mathematical rigor, the program
cannot be considered correct
As a practical matter, the validity of programs is still established by
testing. Testing of computer programs is an art rather than a science,
but that does not mean that there is nothing in it to learn
6. Simple strategies for Developing Algorithm.(Iteration, Recursion)
Iteration and recursion are key computer science techniques used in
creating algorithm and developing software.
In simple terms, an iterative function is one that loops to repeat some
part of the code, and a recursive function is one that calls itself again
repeat the code.
Using a simple for loop to display the numbers from one to ten is an
iterative process. Solving the eight queens problem is a simple
recursion process
Recursion is a problem solving approach by which a function calls itself
repeatedly untill some specified condition has been satisfied. Recursion
splits a problem into due or more simpler version of itself
Advantages of Rewrsive function:
It is written with less number of statements
Recursion function are effective where the terms are generate
successively to computer a value
If require few variable which makes problem clean
It is useful for branching process
Difference between recursion and iteration:
Recursion Iteration
Repetition id achived through Iteration is explicity a repetition
repeated function calls structure
Recursion terminates when a base Iteration terminates when the loop
case is recongoized continuation lest becomes false
Recursion causes au other copy of Iteration normally occurs within a
the function and hence a loop, so the extra memory
considerable memory space assignment is omitted
occupied
Ex:
The factorial of an integer n which is written as n! is the result of
multiplying n by all the positive integers less than n, for instance
3!=3*2*1, which result in 6, and 4!=4*3*2*1,which result in 24
function factorial (n){ return (n==0)?:n* fa(n-1):}
As you can see, part of definition of the result of factorial performed on
a smaller integer. By calling itself, it can multiply the number by each
position number less that it and then return the final result. Recursive
function can be useful in other calculations, such as calculating
fibonacci number or the greatest common divisor.
Another good example is method to calculate the fibonacci number. By
definition, the first two fibonacci number are o and 1, and each
subsequent number s the sum of the previous two;
In mathematical terms, the sequence fn of fibonacci number defined by
the recursive statement
Example algorithm for recursion:
Factorial of a given number using recursion
Reverse of a number
Fibonacci series
Convert the string into lowercase
Sum of digits
Armstrong number
Example algorithm for recursion:
Factorial of a given number using recursion
GCO using recursion
Tower of Hanoi using recursion
7. Write program:
i. To find an integer number in a range
ii. Tower of Hanoi
Algorithm Guess Number:
(# Problem description` Guess the correct number.
# input: key element hum.
output: message about the Gussing made
num= random randint(1,10)
while True;
Print ("Guess a number between 1 and 10)
Read (1)
if i==num
Print ("you have Gussed correct number!!!)
break
else if i<num
Print ("number is lower inter higher`)
else if i>num
Flow chart:
start
Create a num
random
between 1-10
Read guess
number from
user
If
Guess> Number is
num higher
If
Guess>n Number is
um lower
If
Guess>
num
Winner ( i )
Program:
imput random
BOUNDS= (1,100)
TRIES-ALLOWED=5
The number= random,randint (*BOUNDS)
Print("If welcome to "Gruess my number"In`")
Print ("I'm thinking of a number between %d and %d;%BOUNDS)
Print ("Try to guess it in as few attempts as possible.(n")
for tries in range (TRIES-ALLOWED);
Guess=int(input("Take a guess;"))
i. guess>The-number;
print ("lower")
elif guess<The-number;
print ("Higher.....")
else;
print("you gussed if! The number was %d"% (The-number))
print("And it only took you %d tries /n/n"%(triestl));
break
else;
print("you failed to guess in time !/n/n")
# Admittedly a controted way to write a statement
that works in both python 2 and 3
try;
input ("process the enter key to exit")
execpt
pass
write (from,to);
return;
}# move top n-1 disks from A to B using C towers
(n-1),from.aun,to);
Write (from,to);
#More remaining disk from B to C using A towers
(n-1,aux,to,fr);
Output
Welcome to " Guess My Number"!
I'm thinking of a number between 1 and 100
Try to guess it in as few attempt as possible
Take a guess :3
Higher
Take a guess :4
Higher,,,,,,
Take a guess ; 99
you guessed it!The number wall 99
And it only took you 4 tries !
Press the enter key to exit.
Algorithm of Tower of Hanoi:
{ write ("/n/n Enter the total numbers of disk");
Read (n);
towers(n,'A','C','B');
}
Subroutime towers (n,fr,to,aux)
{
# if only one disk has to be moved
if n==1
{
Flow chart:
start
Enter n (i.e)
number of
disks
Call the
function towers
(n, A, B, C)
stop
If
N=1?
Print move disk
from fr to aux
Call the
function towers
( n-1, fr to aux
)
Print moves disc
from n fr to aux
Call the fonction
with towers ( n-1,
aux to fr )
Program:
def-init-(self);
self counter=0
def hanoi (self,n,a,c,b).
if n==1;
self. countes+=1
print('{0}->{1}'. formal (a,b))
else;
self, hanoi(n-1,a,b,c,)
self,hanoi(1,a,c,
self,hanoi(n-1,b,c,a)
towes=Tower()
tower,hanoi(3,"a","b","c")
Output:
a->b
a->c
c->a
a->b
b->c
b->a
a->b
ix. Find Miuinum in a list python:
x=[2,3,5,9,1,o,8,7]
def my-min(sequence);
low= sequence [0]#used to start with some value
for i in sequence;
if i<low;
low=i
return low
print my-min (x)
Output:
2
ii. Find Maximum in a list python:
x=[2,3,5,9,1,0,8,7]
high=sequence[0]#need to start with some value
for i in sequence
if i>high
high=i
return high
print my max (x)
Output:
9
Flow chart:
start start
Read the value Read the value
of list of list
If If
i<low i>high
low=i high=i
Return low Return high
stop stop
Flow chart of minimum Flow chart of maximum
In list In list