Python - Unit 1-New-Final
Python - Unit 1-New-Final
1.1. ALGORITHM
An algorithm is defined as a step by step procedure for solving a problem. It is a ordered
set of rules to solve a problem. An algorithm is a representation of a solution to a problem. It 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.
Algorithm
Input A step by step method Output
for solving a problem
Definiteness
Instruction must be clear, user defined & Precise. There should not be any ambiguity.
Input
An algorithm has zero or more, but only finite number of inputs, zero inputs. Eg: ASCII
character of 0-225.
1.2 Problem Solving and Python Programming
Output
An algorithm has one or more output.
Effectiveness
An algorithm should be effective that means each of the operation to be preformed in
algorithm should be computer programming language independent.
Uniqueness
Result or each steps are uniquely defined and only depend on the input and result of the
preceding steps.
Generality
Algorithm should apply to set of input, rather than single input.
Feasibility
It must be possible to perform each instructions.
1.2.2. State
Stored data are regarded as part of the internal state of the entity performing the algorithm.
The state is stored in one or more data structures. For such computational process, the algorithm
must
Algorithmic Problem Solving 1.3
be rigorously defined and it must be specified in the way that it applies in all possible
circumstances. Data Structure specify the arrangement of data in a particular format.
1.2.4. Function
A function is a sequence of instructions that perform a task, bundled as a unit. Functions
can accept input arguments and produce output values. A function in Python is defined by using
the keyword def, after which the name of the function follows, terminated by a pair of braces
(which may or may not contain input parameters) and, finally, a colon (:) signals the end of the
function definition line. Immediately afterwards, indented by four spaces, we find the body of the
function, which is the set of instructions that the function will execute when called.
Statements
The algorithm consists of finite number of statements.
The time taken to execute all the statements of the algorithm should be finite and within a
reasonable limit.
Sequence Structure
This is the most common form of control structure. Each statement in the program is
executed one after another in the given order. The flow of sequence structure is shown in
Figure.1.1.
Statement 1
Statement 2
Statement n
Selection Structure
The selection control structure is the presentation of a condition and the choice between
two (or sometimes more) actions. The choice made depends on whether the condition is true or
false. It is also called a decision, one of the three basic logic structures in computer. This structure
is sometimes referred to as an if-then-else because it directs the program to perform in this way: If
Condition A is True then perform Action X else perform Action Y. The flow of sequence structure
is shown in Figure.1.2.
True False
Algorithmic Problem Solving 1.5
Figure 1.2. Selection structure.
1.6 Problem Solving and Python Programming
Algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Iteration Structure
The iterative process is also called as repetition or looping. It carries out a particular action
over and over again until some condition is met. A loop is created to return the program to where
the repetition has started for as long as it takes until the condition is met.
Algorithmic Problem Solving 1.7
There are two ways of testing to see if the condition is met: pre-test loops, and post-test
loops. In pre-test loops, the condition is tested at the beginning of the loop. If the condition fails,
the looping process will never carried out. Here the loop is operated only when condition is met.
Pre-test loop ends when the condition fails.
Post-test loops test the condition at the end of the loop. The looping process is executed
first whether the condition is true or false and will keep repeating until the condition is met. This
loop ends when the condition is true. The structures of pre-tested and post-tested loops are shown
in Figure.1.3.
True False
False
True
Listing Change
Product Check
Step 6: Increment N by 1
Step 8: Stop
Algorithmic Problem Solving 1.9
1.2.1 PSEUDOCODE
Pseudocode (pronounced SOO-doh-kohd) is a kind of structured English for representing
algorithms and is a “text-based” detail design tool for human understanding rather than machine
understanding. It allows the designer to concentrate on the logic of the algorithm without
worrying about the details of language syntax.
Once the pseudo code is prepared, it is rewritten using the syntax and semantic rules of a
programming language.
Sequence
It is indicated by writing one statement after another, each statement on a line by itself,
and all statements aligned with the same indent. The actions are performed in the order in which
they are written, from top to bottom.
Common Keywords
Input: READ, INPUT, OBTAIN, GET
Output: PRINT, OUTPUT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP
Examples
(i) Pseudo code for computing the area of a rectangle.
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
PRINT area
Selection
It is a decision (selection) in which a choice is made between two alternative courses of
action and it comprises of the following constructs:
• IF-THEN-ELSE
• CASE...ENDCASE
IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords:
◦ IF, THEN, ELSE, and ENDIF.
The ELSE keyword and “sequence 2” are optional. If the condition is true, sequence 1 is
performed, otherwise sequence 2 is performed.
Examples
(i) Pseudo code to check whether the number is odd or even.
READ number
IF number MOD 2 = 0 THEN
DISPLAY “Number is Even”
ELSE
DISPLAY “Number is Odd”
ENDIF
(ii) Pseudo code to check whether the given non-zero number is positive or negative.
READ number
IF num is less than 0 THEN
PRINT num is negative
ELSE
PRINT num is positive
ENDIF
1.12 Problem Solving and Python Programming
CASE
CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE
The OTHERS clause with its default sequence is optional. Conditions are normally
numbers or characters indicating the value of “expression”, but they can be English statements or
some other notation that specifies the condition under which the given sequence is to be
performed. A certain sequence may be associated with more than one condition.
Examples
(i) Pseudo code for simple calculator
READ n1, n2
READ choice
CASE choice OF
+ : PRINT n1+n2
– : PRINT n1-n2
* : PRINT n1*n2
/ : PRINT n1/n2
ENDCASE
B : gradepoint = 8
C : gradepoint = 7
D : gradepoint = 6
E : gradepoint = 5
U : gradepoint = 0
ENDCASE
DISPLAY gradepoint
Repetition
It is a loop (iteration) based on the satisfaction of some condition(s). It comprises of the
following constructs:
• WHILE...ENDWHILE
• REPEAT...UNTIL
• FOR...ENDFOR
WHILE...ENDWHILE
It is a loop (repetition) with a simple condition at its beginning. The beginning and ending
of the loop are indicated by two keywords WHILE and ENDWHILE.
The loop is entered only if the condition is true. The “sequence” is performed for each
iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as
long as the condition is true.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
WHILE n is less than or equal to 100
DISPLAY n
INCREMENT n by 1
ENDWHILE
1.12 Problem Solving and Python Programming
(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
WHILE Number is not zero
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
ENDWHILE
PRINT Sum
REPEAT...UNTIL
It is a loop with a simple condition at the bottom. This loop is similar to the WHILE loop
except that the test is performed at the bottom of the loop instead of at the top. Two keywords,
REPEAT and UNTIL are used.
The “sequence” in this type of loop is always performed at least once, because the test
is peformed after the sequence is executed. At the conclusion of each iteration, the condition is
evaluated, and the loop repeats if the condition is false. The loop terminates when the condition
becomes true.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
REPEAT
DISPLAY n
INCREMENT n by 1
UNTIL n is greater than 100
(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
Algorithmic Problem Solving 1.13
REPEAT
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
UNTIL Number is zero
PRINT Sum
FOR...ENDFOR
FOR is a “counting” loop. This loop is a specialized construct for iterating a specific
number of times, often called a “counting” loop. Two keywords, FOR and ENDFOR are used.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
FOR n=1 to 100
DISPLAY n
ENDFOR
(ii) Pseudo code to input ten numbers and print the sum.
INITIALIZE sum to 0
FOR n=1 to 10
INPUT number
COMPUTE sum as sum+number
ENDFOR
DISPLAY sum
Nested Constructs
The constructs can be embedded within each other, and this is made clear by use of
indenting.
Nested constructs should be clearly indented from their surrounding constructs.
Examples
(i) Pseudo code to find the smallest among three numbers using nested IF construct.
READ the three numbers a, b, c.
1.14 Problem Solving and Python Programming
Invoking Subprocedures
To call subprocedures (functions), CALL keyword is used with the following structure:
Examples:
CALL SumAndAvg WITH NumberList
◦ Calls a function SumAndAvg with NumberList as an argument. This function does
not return any value.
CALL SwapItems WITH CurrentItem and TargetItem
◦ Calls a function SwapItems with CurrentItem and TargetItem as arguments. This
function does not return any value.
CALL getBalance RETURNING BalanceAmt
◦ Calls a function getBalance which returns BalanceAmt as its return value. This
function does not take any argument.
1.2.2 Flowchart
Flowchart is a diagrammatic representation of an algorithm or a stepwise process, showing
the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts
are used in designing or documenting a process or program. In other words, a flow chart, or flow
diagram, is a graphical representation of a process or system that details the sequencing of steps
required to create output. A flowchart is a picture of the separate steps of a process in sequential
order.
Flowchart is very helpful in writing program and explaining program to others. Flowchart
makes us to understand the problem unambiguously. It is often used by programmer as a program
planning tool for organizing a sequence of step necessary to solve a problem by a computer.
GUIDELINES
The following are some guidelines in flowcharting:
(a) In drawing a proper flowchart, all necessary requirements should be listed out in
logical order.
(b) The flowchart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
(c) The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
(d) Only one flow line should come out from a process symbol.
or
(e) Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, should leave the decision symbol.
=0 =0
(f) Only one flow line is used in conjunction with terminal symbol.
(g) Write within standard symbols briefly. As necessary, you can use the annotation
symbol to describe data or computational steps more clearly.
(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(i) Ensure that the flowchart has a logical start and finish.
(j) It is useful to test the validity of the flowchart by passing through it with a simple test
data.
sum ← a+b
Display sum
stop
Flowchart representation to find all the roots of a quadratic equation ax 2+bx+c=0
Start
Calculate discriminant
D←b-4ac
True is
False
D ≥ 0?
r1←(-b+ 𝐷)/2𝑎 ip←-b+/2𝑎
r2←(-b+ 𝐷)/2𝑎 rp← 𝐷)/2𝑎
x1←rp+j ip
x1← rp-j ip
Display r1 and r2
Stop
fterm←0, sterm←1
is False
sterm ≤
1000?
True
Display sterm
temp←sterm
sterm←sterm+fterm
Stop
fterm←temp
1.2.3 Programming Language
Representation of Algorithm using Programming Language
Algorithms describe the solution to a problem in terms of the data needed to represent
the problem instance and the set of steps necessary to produce the intended result. Programming
languages must provide a notational way to represent both the process and the data. It also provide
control constructs and data types.
Fig Programming
Yes sum=sum+i
i<=100 i=i+1
No
The flowchart clearly shows the repetition. The flow-line emerging from the rectangle
wraps back to the decision that is tested each time through the loop until the decision becomes false.
Then the while structure exits and control passes to the next statement in the program.
min= numbers[0]
True
No
if i<min
Yes
min= i
Stop
• 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 left to right.
Once the position is found, the cards from that position are moved to the next higher
indexed position and in that order.
Algorithm
1. Start
2. Ask for value to insert
3. Find the correct position to insert, If position cannot be found ,then insert at the end.
4. Move each element from the backup to one position, until you get position to insert.
5. Insert a value into the required position
6. Increase array counter
7. Stop
Pseudo Code
READ the list of sorted cards
READ newcard
SET pos to 0
WHILE (pos < numberOfCards) and (CARDS [pos] <= newcard)
INCREMENT pos
ENDWHILE
IF pos < numberOfCards then
INCREMENT numberOfCards by 1
FOR counter = last position used to pos by -1
SET CARDS [counter + 1] to array CARDS [counter]
ENDFOR
ENDIF
SET CARDS [pos] to newcard
Flowchart for inserting a card in a list of sorted cards
Start
position=1
No
position<length
Yes
location = position
No location > 0
position=position+1 && cards [location]
< cards [location-1]
Yes
Swap cards [location] < cards[location-1]
location= location-1
Stop
1.6.3.Guessing Game
Problem: Guessing Game – guessing a number within a range of numbers.
Algorithm:
Step 1. Generate a random number in between 1 and 100.
Step 2. Prompt the user for a guess number.
Step 3. Determine if the guessing number is
Step 3. (a). Equal to the random number: If it is, output a message that says the guessing is
correct and go to step 4.
Step 3. (b). Less than the random number: If it is,
(i) Output a message “Too low,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 3. (c). Greater than the random number: If it is,
(i) Output a message “Too high,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 4. Stop.
Pseudo code to guess an integer number in a range
This task allows a player to guess a number that lies between 1 and 100. The code should
keep repeating until the player guesses the correct number. The number guessed by the system in
the following pseudo code is 45.
Pseudo Code
READ number from player
WHILE number is not equal to 45
IF number is less than 45 THEN
PRINT Your guess is too small.
ELSE IN number is greater than 45
PRINT Your guess is too high.
ENDIF
IF number does not fall between 1 and 100 THEN
PRINT Guess a number between 1 and 100
ENDIF
READ number
ENDWHILE
PRINT Your guess is correct
Flowchart:
Start
num=input random
number
guess=input user
guess
Yes No Yes
Does Is
guess=num guess>num?
No
Print “Too
Yes Do you high”
want
to
Do you No
No give
up?
Yes
End
1.6.4.Towers of Hanoi
Problem:
Tower of Hanoi is a mathematical puzzle with three rods and ‘n’ numbers of discs. These
rings are of 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.
2 DISKS
A B C
A B C A B C A B C
Declare n
End
Flowchart: Function towerfun()
M
n=1
?
Return
Algorithm:
Step 1: Set max to 0 and min to 0.
Step 2: For each number x in the list L, compare it to max.
Step 2.a: If x is larger, set max to x. Else set min to x
Step 3: Display max and min
Step 4: Stop
Initialize X< 0
Increment X by 1
Print X
Yes
X < 20
No
End
Read F
C = 5/9*(F-32)
Print C
End
Flowchart to determine and output whether number N is Even or Odd
Start
Input N
Remainder = N
Modulo 2
Yes No
Remainder = 0?
Output
Answer
End
Input M1,
M2m M3, M4
Grade =
(M1+M2+M3+M4)/4
Yes No
If Grade < 60
End
Algorithmic Problem Solving 1.35
Terminal
Disadvantages:
• It cannot be prepared for difficult programs
• Alterations and modifications cannot be done easily
Disadvantages:
• It is not visual.
Algorithmic Problem Solving 1.37
13. Develop an algorithm and draw the flowchart to get marks for 3 subjects and declare
the result. If the marks >= 35 in all the subjects the student passes else fails.
Algorithm:
1. Start.
2. Declare three variables m1, m2, m3.
3. Read marks of three subjects m1, m2, m3.
4. If m1 >= 35 goto step 5 else goto step 7
5. If m2 >= 35 goto step 6 else goto step 7
6. If m3 >= 35 print Pass. Goto step 8
7. Print fail
8. Stop
1.38 Problem Solving and Python Programming
Flowchart:
Start
m1 = m2 = m3 =0
No
M1>=35
Yes
No
M2>=35
Yes
No
M3>=35
Yes
Stop
14. Develop an algorithm and draw the flowchart to compute average of three numbers.
Algorithm:
1. Start
2. Read numbers a,b,c
3. Compute the average as (a+b+c)
4. Print average
5. Stop
Flowchart:
Start
Read a, b, c
avg =(a+b+c)/3
Print avg
Stop
Algorithmic Problem Solving 1.39
15. Draw the flowchart for following: read age of a person. If age less than 60 then print
“Not a senior citizen” otherwise print “Senior Citizen”.
Start
Read Age
Yes
Print
Age < 20 Not a
senior
citizen
No
Pr
int
senior
citizen
Stop
Input/Output Connectors
Decision Flow Lines
Box
19. What keywords are commonly used in Pseudocode?
Input: READ, INPUT, OBTAIN, GET
Output: PRINT, OUTPUT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP