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

Python UNIT 1

Python

Uploaded by

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

Python UNIT 1

Python

Uploaded by

jankar123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

UNIT I

ALGORITHMS AND PROBLEM SOLVING


Algorithms, building blocks of algorithms
(instructions/ statements, state, control flow,
functions), notation (pseudo code, flow chart,
programming language), algorithmic problem
solving, simple strategies for developing
algorithms (iteration, recursion)
ALGORITHMS
• An algorithm is a set of instruction for a specific task .
• An algorithm is a set of instructions used for solving problems
in a step-by-step manner
✔ Algorithm is a finite and ordered sequence of steps.
✔ It can be implemented in many different languages by using
different methods and programs.
✔ It is a description of a process independent of any
programming language.
Characteristics of Algorithm
• Each and every instruction should be precise and
unambiguous.
• The instruction should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• It should be written in sequence.
• It looks like normal English.
• The desired result should be obtained only after the
algorithm terminates.
Qualities of Good Algorithm
• Time
• Memory
• Accuracy
• Sequence
• Generability
Building blocks of an algorithm
• Statements
• State
• Control flow
• Functions
Statements/Instructions
• Commands given to the computer to perform
specific tasks
• A program consists of set of instructions
• The instructions / statements can be categorized as
– Simple statements – Used by sequence control
structure. Eg: a = 5, Read the input, etc.
– Compound statements – Used by decision and
looping control structures.
State
⮚ An algorithm is deterministic automaton for
accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
⮚ Stored data is regarded as part of the internal
state of the entity performing the algorithm.
⮚ The state is stored in a data structure.
Control flow
1. Sequential control
It means that the steps of an algorithm are carried out in a
sequential manner,where each step is executed exactly once.

2. Selection or conditional control


In selection control only one of a number of alternative
steps is executed based on the condition.

3. Repetition or control flow


One or more steps are performed repeatedly .
This logic is used for producing loops in a program logic
when one or more instructions may be executed several times or
depending on some conditions.
Sequential Control
• It means that the steps of an algorithm are carried out in a
sequential manner, where each step is executed exactly once.
Example – Sequential Control
• Step 1: Start
• Step 2: Read the radius (r) of the circle
• Step 3: Area 3.14*r*r // calculation of area
• Step 4: Print Area
• Step 5: End
Selection or conditional control

• In selection control only one of a number of


alternative steps is executed based on the
condition.
Example – Conditional Control
Step 1: Start
Step 2: Read the values of A and B
Step 3: If (A >B) then Print A is greater
Step 4: else Print B is greater
Step 5: End
Repetition or control flow

• One or more steps are performed repeatedly .


• This logic is used for producing loops in a
program logic when one or more instructions
may be executed several times or depending
on some conditions
Example - Repetition
Step 1: Start
Step 2: Read the value of n
Step 3: Initialize i = 1
Step 4: while( i <= n ),else goto step 5
Step 4.1: print i
Step 4.2 i=i+1
Step 5: End
Functions
• Functions performs well-defined specific tasks.
• They are self contained modules of code that takes input and
returns a output
• It can be called any number of times. That is, when a function
is written it can be called any number of times
• The functions change the flow of control of a program
• When a function is called, the current flow is switched to the
function. Once the function gets executed, the flow returns
back to the next line of code
Actual and Formal parameter
• Have two parameters – Actual and Formal parameter
– Actual Parameter – the list of parameters actually passed during the
function call
– Formal Parameter – acts as a placeholder for the actual parameters
during function definition  Advantages – Reduce memory by
providing code reusability
Different Approaches of Designing an Algorithm

• Two main approaches to design an algorithm are


• Top-down approach
• Bottom-up approach
Different Approaches of Designing an Algorithm
Top – Down Approach Bottom – Up Approach
Starts by dividing the Starts by designing the most
complex algorithm into one basic or concrete modules
or more modules and then proceed towards
designing higher level
modules
Iterated until desired level of Repeated until the design of
module complexity is the complete algorithm is
achieved obtained
High level functions are Groups several low level
decomposed into one or functions to form a high level
more low level functions function
Information Hiding is Information Hiding is
ignored allowed
Procedural programming Object Oriented
languages like C, FORTRAN, programming languages
etc., follow this approach like C++, JAVA, etc., follow
this approach
Mainly used in Mainly used in testing
documentation, generating
test cases, implementation
and debugging
Algorithm for swapping two values
Step 1: Start
Step 2: Input first number as A
Step 3: Input first number as B
Step 4: Set temp=A
Step 5: Set A=B
Step 6: Set B=temp
Step 7: Print A,B
Step 8: End
Algorithm to find whether a number is even or
odd:
Step 1: Start
Step 2: Input number as A
Step 3: IF A%2 =0
Print “Even”
ELSE
Print “odd”
[END OF IF]
Step 4: End
Notations
Pseudocode
• Pseudocode is a kind of structured english for designing
algorithm.
• Pseudocodes came from two words.
– Pseudo -> imitation
– Code -> refer to instructions.
• Pseudocode cannot be compiled nor executed, and there
are no real formatting or syntax rules.
• The benefit of pseudo code is that it enables the
programmer to concentrate on the algorithms without
worrying about all the syntactic details of a particular
programming language.
• It is a mix of programming language and preferred human
language.
Rules for Pseudocode

• Write only one statement per line


• Capitalize initial keyword
• Indent to show hierarchy
• End multiline structures
• Keep statements language independent
One Statement Per Line

• Each statement in pseudocode should express just one


action for the computer.
• If the task list is properly drawn, then in most cases
each task will correspond to one line of pseudocode.
Task List
Read name, hours worked, rate of pay
Perform calculations
gross = hours worked * rate of pay
Write name, hours worked, gross

Pseudocode
READ name, hoursWorked, payRate
gross = hoursWorked * payRate
WRITE name, hoursWorked, gross
Capitalize Initial Keyword
• In the example below note the words:

• READ and WRITE. These are just a few of the keywords to


use, others include:
READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE

Pseudocode
READ name, hoursWorked, payRate
gross = hoursWorked * payRate
WRITE name, hoursWorked, gross
Indent to Show Hierarchy
Each design structure uses a particular indentation pattern
• Loop:
Indent statements that fall inside the loop but not keywords that form
the loop
READ name, grossPay, taxes
IF taxes > 0
net = grossPay – taxes
ELSE
net = grossPay
ENDIF
WRITE name, net
End Multiline Structures
READ name, grossPay, taxes
IF taxes > 0
net = grossPay – taxes
ELSE
net = grossPay
ENDIF
WRITE name, net

See the IF/ELSE/ENDIF as constructed above, the


ENDIF is in line with the IF.

The same applies for WHILE/ENDWHILE etc…


Keep statement Language Independence

• Resist the urge to write in whatever language you are most


comfortable with, in the long run you will save time.
• Remember you are describing a logic plan to develop a
program, you are not programming!
Example- sequence structure
• Set Area
• READ the radius of the circle
• Find the area of the circle using the formula
• Area=3.14*r*r
• WRITE the output area of the circle.
• stop
Example- conditional structure
• Set the variable a,b
• READ the value of a and b
• IF a>b
PRINT the output a is greater
ELSE
PRINT b is greater
ENDIF
• stop
Example- repitition structure
• Set the variable n
• Initialize the value of i=1,
• WHILE(i<=n) true
PRINT i
i=i+1
Repeat while until the condition fail
ENDWHILE
• Stop
Advantages of Pseudocode
• It Can be done easily on a word processor.
• Easily modified.
• Implements structured concepts well.
• It is simple because it uses English-like
statements.
• No special symbols are used
• No specific syntax is used.
• It is very easy to translate its statements to that
for high level languages on a one-for-one basis.
Disadvantages of Pseudocode
• It’s not visual.
• There is no accepted standard, so it varies
widely from company to company.
• Cannot be compiled not executed.
• Beginners find difficult to follow the logic.
The Flowchart
• A graphical representation of the sequence of
operations in an information system or
program.
• Information system flowcharts show how data
flows from source documents through the
computer to final distribution to users.
• Different symbols are used to draw each type
of flowchart.
Flow chart symbols
Rules for drawing a flow chart
• The standard symbols should only be used .
• The arrowheads in the flow chart represents
the direction of flow of control in the problem
• The usual direction of the flow of procedure is
from top to bottom or left to right.
• Only one flow line should come to a process
symbol and only one flow line should be out
from a process symbol.
Example- sequence structure
Example- conditional structure
Example- repetition structure
start

Read n,
Initialize i=1

No While
(i<=n)
yes

Print i

i=i+1

Stop
Common keywords
• Input: READ, OBTAIN, GET
• Output: PRINT, DISPLAY, SHOW
• Compute: COMPUTE, CALCULATE, DETERMINE
• Initialize: SET, INIT
• Add one: INCREMENT
Example- repitition structure
Advantages
• To understand logic clearly
• Better Communication
• Effective analysis
• Effective synthesis
• Effective coding
• Proper program documentation
• Systematic Debugging
• Systematic Testing
• Efficient program maintenance
Dis-Advantages/Limitations
• Complex logic
• Alterations and modifications
• Reproduction
• Cost
• Not known
Programming languages
• Computer programming languages are used to
communicate instructions to a computer.
• They are based on certain syntatic and
semantic rules, which define the meaning of
each of the programming language constructs.
Simple strategies for developing algorithms
(Iteration, Recursion)

• Iteration - an iterative function is one that loops to


repeat some part of the code
• Recursion - a recursive function is one that calls itself
again to repeat the code.
– Recursion is a problem solving approach by which a function calls
itself repeatedly until some specified condition has been satisfied.
Recursion splits a problem into one or more simpler versions of itself.
• Example algorithm for Iteration Process
– Factorial of a given number
– 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
– GCD using recursion
– Tower of Hanoi using recursion
Iteration:- Reverse a number
step 1: Start
step 2: Initialize reverse=0.
step 3: Read digit
step 4: Check whether digit>0 then go to step 5
else go to step 9
step 5: reverse =reverse *10
step 6: reverse=reverse+digit%10
step 7: digit =digit/10
step 8: Go to step 4
step 9: Print reverse
step 10: Stop
start

Read digit,
Initialize
reverse =0
No
While
(digit>0)

yes

reverse =reverse *10


reverse=reverse+digit%10
digit =digit/10

Print
reverse

Stop
pseodocode
• Set the variable reverse, digit
• Initialize reverse=0
• READ the value of digit
• WHILE (digit>0) then
reverse =reverse *10
reverse=reverse+digit%10
digit =digit/10
Repeat while until the condition fail
ENDWHILE
• PRINT reverse
• Stop
Iteration:- factorial
step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. if or check whether (i<=n) else goto
step 5. fact=fact*i
step 6. i=i+1
step 7: goto step 4
step 8. Print fact
step 9. Stop
PSEUDOCODE
Start
READ the value of n
Initialize i and fact
IF(i<=n) THEN
fact=fact*i
i=i+1
Repeat while until the condition fail
Print fact
END WHILE
Stop
IIUSTRATIVE EXAMPLES
Iteration: minimum number in a list
1. Start the program
2. Read the upper limit array ‘n’
3. Read an array a[] of n numbers.
4. Assign first array value to variable ‘min’ min-
>a[0]
5. For i=1 to n
6. If a[i]<min then min=a[i]
7. Repeat step 5 and 6 until condition fails
8. Print min element
9. stop
start

Read n

for i=0 to n

Read i

Min=a[0]
no
for i=1 to n
yes
If(a[i]< no
min)
yes
Min=a[i]

Print
min

stop
pseudocode
• Set initial i
• READ n
• READ array a[] of n numbers
• Set min=a[0]
• FOR i=0 to n
– IF a[]i]<min
– then min=a[i]
• ENDFOR
• Print min
• stop
Recursion:- factorial
• Step 1: Start
• Step 2: Read number n
• Step 3: Call factorial(n)
• Step 4: Print factorial f
• Step 5: Stop
factorial(n)
• Step 1: If n==1 then return 1
• Step 2: Else f=n*factorial(n-1)
• Step 3: Return f
Flowchart
start Call factorial n

Read n
If(n==1) yes Return 1

Call factorial n no

f=n*factorial(n-1)
Print f
Return f

stop
pseudocode
Start
READ number n
Call factorial(n)
Factorial(n)
IF n==1 THEN return 1
ELSE f=n*factorial(n-1)
RETURN f
ENDIF
WRITE factorial f
Stop
Difference between recursion and
iteration:
PROBLEM SOLVING METHODOLOGY
Definition

Analysis

Design

Coding

Testing

Documentation

Maintanence
ALGORITHMIC PROBLEM SOLVING
STEPS FOR ALGORITHMIC PROBLEM
SOLVING
1.Understanding the Problem
⮚ The problem given should be clearly and completely
understood.
2.Ascertaining the Capabilities of the Computational
Device
⮚ Sequential algorithms
⮚ Parallel algorithms
⮚ The capabilities of the computing device should be
known.
⮚ Speed, Memory availability of the device are noted.
STEPS FOR ALGORITHMIC PROBLEM SOLVING
(Contd)
3. Choosing between Exact and Approximate Problem Solving
⮚ Solving the problem exactly is called an exact algorithm.
⮚ Solving it approximately is called an approximation algorithm.
4.Deciding on appropriate Data Structures
⮚ Data type is a well-defined collection of data with a well
defined set of operations.
⮚ Data structure is basically a group of data elements that are
put together under one name.
Elementary data structures:
List: Allow fast access of data.
Sets: Treats data as element of a set. The operations such as
intersection , union and equivalence.
Dictionaries: Allows data to be stored as a key-value pair.
STEPS FOR ALGORITHMIC PROBLEM
SOLVING (Contd)
5. 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.
6. Methods of Specifying an Algorithm
⮚ Free and also a step-by-step form
⮚ Pseudocode.
⮚ Flowcharts.
STEPS FOR ALGORITHMIC PROBLEM
SOLVING (Contd)
7. Proving an Algorithm’s Correctness
⮚ Writing an algorithm is not enough.
⮚ You need to prove that it computes solutions for all the possible
valid inputs.
⮚ This process is called algorithm validation.
⮚ Algorithm validation ensures that the algorithm will work correctly
irrespective of the programming language in which it will be
implemented.
8. Analyzing an Algorithm
⮚ Efficiency is an important characteristic of any algorithm.
There are two kinds of algorithm efficiency:
⮚ Time efficiency, indicating how fast the algorithm runs.
⮚ Space efficiency, indicating how much extra memory it uses.
9. Coding an Algorithm
Inserting a element from a sorted element

Algorithm:
• Step 1: Start the program.
• Step 2: Read a [], n, item, i=n-1
• Step 3:Check whether WHILE (item<a[i] && i>=0) then a
[i+1] = a[i] else go to Step 4
• Step 4: a [i+1] = item
• Step 5:Increment n
• Step 6:For i=1 to n
• Step 7:Write a[i]
• Step 8:Stop the program
Pseudocode
READ a [20], n, item, i.
Get the value of array a [].
Get the value to be inserted in the sorted elements.
i= n-1;
WHILE (item<a[i] && i>=0)
a [i+1] = a[i]
i--
ENDWHILE
a [i+1] = item
n++
WRITE the Insertion Array.
FOR i = 0 to n
WRITE a[i].
ENDFOR
Start

Read a[],item

i=n-1

While(item
<a[i]&&i>0 no a[i+1]=item
) n++
yes
a[i+1]=a[1]
i--

for i=0 to n

write a[i]

Stop
Guess an integer number in a range
Algorithm:
Step 1: Start the program
Step 2: Read an ‘n’ number.
Step 3: Read an Guess number.
Step 4: if Guess > n ; Print “ Your Guess too high”.
Step 5: elseif Guess < n ; Print “ Your Guess too low”.
Step 6: elseif Guess = = n; Print “Good Job”.
Step 7: else print “Nope”.
Step 8:Stop the program.
Pseudocode:
READ an ‘n’ number
READ an Guess number
Guess = 20
IF Guess > n
WRITE “ Your Guess too high”
ELSEIF Guess < n
WRITE “ Your Guess too low”
ElSEIF Guess = = 20
WRITE “Good Job”
ElSE
WRITE “NOPE”
Towers of hanoi
• Rules:
– Only one disk can be moved at a time.
– Each move consists of taking the upper disk from
one of the stacks and placing it on top of another
stack.
– No disk may be placed on top of a smaller disk.
Towers of Hanoi
Algorithm:
Step 1: Start the program
Step 2: procedure Hanoi(disk, source, dest, aux)
Step 3: if disk = = 1
Step 3.1 : Move disk from source to dest
Step 4: else
Step 4.1 : Hanoi(disk -1, source, aux, dest)
Step 4.2 : Move disk from source to dest
Step 4.3: Hanoi(disk – 1, aux, dest, source)
Step 5:endif
Step 6:Stop the program
Towers of Hanoi
Pseudocode:
Procedure Hanoi(disk, source, dest, aux)
IF disk = =1 then
Move disk form source to dest
ElSE Hanoi(disk -1, source, aux, dest)
Move disk from source to dest
Hanoi(disk – 1, aux, dest, source)
ENDIF
END Procedure
start

Hanoi(disk,source,
Read
dest,aux
disk,sourcr,dest,aux

Hanoi(disk,source, Move disk


Yes If
dest,aux) from source to disk==
dest 1

Display result No
Hanoi(disk-
1,source,aux,dest)
Stop

Move disk from


source to dest

Hanoi(disk-
1,aux,dest,source)
Assignment
• to check whether the given year is leap or not.
• Find the Largest Number Among Three Numbers
• to Check if a given Integer is Odd or Even
• to Check if a given Integer is Positive or Negative
• to Read Two Integers M and N & Swap their Values

You might also like