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

Problem Solving and Python Programming

The document outlines the fundamentals of algorithmic problem solving and Python programming, covering topics such as algorithms, programming steps, and Python's features and data types. It emphasizes the importance of algorithms in problem-solving and provides a structured approach to programming, including the use of Python functions and control flow. Additionally, it discusses the history of Python, its applications, and the distinctions between interactive and script modes of execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Problem Solving and Python Programming

The document outlines the fundamentals of algorithmic problem solving and Python programming, covering topics such as algorithms, programming steps, and Python's features and data types. It emphasizes the importance of algorithms in problem-solving and provides a structured approach to programming, including the use of Python functions and control flow. Additionally, it discusses the history of Python, its applications, and the distinctions between interactive and script modes of execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 205

Problem Solving and

Python Programming
Objective

 Understanding of algorithmic problem solving


 Read & Write Simple Python programs
 Python programs with conditional and loops
 Python functions and call them
 Python data structures
 Input/Output with files in python
05/28/2025
UNIT I

ALGORITHMIC PROBLEM SOLVING 9


Algorithms, building blocks of algorithms (statements, state,
control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion).
Illustrative problems: find minimum in a list, insert a card in a
list of sorted cards, guess an integer number in a range, Towers
of Hanoi.

05/28/2025
How a software get developed ?

1.Planning
2.Designing
3.Programming (Coding)
4.Testing
5.Deployment

For Example : Mobile Banking 05/28/2025


What is program?

A program is a set of instructions written by a programmer. The program contains detailed


instructions and complete procedures for performing the relevant tasks.

05/28/2025
What is programming ?

Programming involves creativity, analytical thinking, knowledge in the language in which coding or
the programming is done.

Steps Involved in Programming


1. Identify the problem
2. Analyzing the Problem
3. Algorithm design
4. Pseudo code conversion
5. Flowchart
6. Coding
7. Debugging
8. Testing
9. Final output 05/28/2025
10. Documentation
Algorithm

 Definition
 Example
 Characteristic of algorithm
 Qualities of an algorithm
 Representation of algorithm
 Advantages of algorithm
 Disadvantages of algorithm

05/28/2025
Problem

Algorithm

Input Computer Output

05/28/2025
Definition

 Algorithm is defined as a step by step procedure for solving any problem.


 It is also a precise rule specifying how to solve a problem.
 An algorithm is a sequence of finite instructions often used for calculation and data
processing.

05/28/2025
Examples:

 Algorithm for Find the area circle.


Step 1: start
Step 2: Read the value of radius r
Step 3: Calculate Area=3.14*r*r
Step 4: Print the area of the circle
Step 5: Stop

05/28/2025
Consider the sample data r=5
Area = 3.14*5*5
Area =78.5

05/28/2025
Every algorithm must have five essential
properties:
 Inputs Specified: An algorithm must have zero or more inputs
 Output Specified: An algorithm has one or more outputs which
specifies relations to the inputs
 Definiteness: Every details of each step must be clearly specified
 Effectiveness: All operation to be performed must be sufficiently
basic that they can be done exactly and in finite
length.
 Finiteness: An algorithm must always terminate after a finite number
of steps

05/28/2025
Characteristic of Algorithm
 An algorithm can be defined as a sequence of definite and effective instruction which terminates with the
production of correct output from the given input.
 An algorithm is not a computer program it is one of the basic tool in problem solving.
 An algorithm has the following characteristic
 Algorithm has a finite number of inputs.
 Every instruction should be unambiguous (clear) and Precise.
 Ensure that the algorithm has proper termination.
 Effectiveness of each step is very important.
 The desired output must be obtained only after the algorithm terminates.
 The algorithm should be written in sequence.

05/28/2025
Qualities of an algorithm

 The different algorithm may perform the same task with different set of instruction.
 Some algorithm is considered as the better tool to solving the problem.
 The algorithm is written in such a way that it optimizes all necessary conditions

05/28/2025
The factors that determine the quality of
algorithm are
 Accuracy : Algorithm should provide accurate result than other.
 Memory : It should require minimum computer memory.
 Time : The time taken to execute any program is considered as a main
quality. Lesser the time taken better than quality.
 Sequence : The procedure of an algorithm must be in a sequential
form.

05/28/2025
Representation of Algorithm

 Algorithm has a starting point and a final point. Between these two points are instruction
that solve the problem.
 Algorithm often have steps that repeat or require decision (such as logic or comparison).
 Algorithm can be expressed in any language from natural languages (like English. French
etc) to programming languages (like Basic. Fortran. Python. Etc..)
 Algorithm is the basic for most of the programs.
 Each rule in an algorithm is written in a programming language.
 All these rules are collectively called a program.

05/28/2025
Advantages of algorithm

 It makes easy to understand about the solution of the given problem.


 It uses a definite procedure to solve a problem.
 It does not dependent on any programming language therefore it is very easy to understand.
 It is written in a sequence form. So it is easy to debug.
 By using algorithm. The problem can be sub-divided into smaller piece. So that it is easy to convert into any
programming language.

05/28/2025
Disadvantages of algorithm

 Algorithm is not a computer program. It is rather a concept of how a program should be


written.
 It is time consuming an algorithm needs to be developed first which is then converted into
flow chart and then into a computer program.
 It is difficult to show branching and looping statements.

05/28/2025
Python Interpreter and
Interactive
UNIT II

DATA, EXPRESSIONS, STATEMENTS 9


Python interpreter and interactive mode; values and types: int,
float, boolean, string, and list; variables, expressions,
statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use,
flow of execution, parameters and arguments; Illustrative
programs: exchange the values of two variables, circulate the
values of n variables, distance between two points.
Brief History of Python

 Invented in the Netherlands, early 90s by Guido


van Rossum
 Named after Monty Python
 Open sourced from the beginning, man-aged by
Python Software Foundation
 Considered a scripting language, but is much more
 Used by Google from the beginning
Python Program

 Python program are composed of modules.


 Modules contain statements.
 Statements contain expressions
 Expression create and process objects.
Features of python

 Open source:
Python is publicly available open source software.
 Easy-to-learn:
Python programming are clear and easy to learn.
Major uses of Python

 Web development.
 Graphical User Interface.
 Internet scripting.
 Embedded Scripting.
 Game Programming.
Python Definition

 Python is a high-level programming language designed to be easy to read and simple to


implement.
 It is open source which means it is free to use even for commercial application.
 Python can run on Mac, windows and Linux System.
Python Interpreter and Interactive Mode

 Python is considered as an interpreted language because programs were executed by one


line after another line.
 There are two ways to use the interpreter.
1.Interactive Mode.
2.Script Mode or Interpreter Mode.
1.Interactive Mode.

 Interactive mode is a command line shell which gives immediate feedback for each
statement.
 The symbol >>> , is a prompt the interpreter uses to indicate that it is running in
interactive mode.
 Interactive mode allows us to test and see the working principle of python.
 Python script usually contains a sequence of statement. If there is more than one statement
the result appear one at a time as the statement executive.
For Examples

>>> print (“Hello World !”)


Output
Hello World !

 Python prompt.
 Python function
 Round brackets parenthesis.
 Function arguments.
 Output
2.Script Mode

 A script mode can store code in a file and it uses the interpreter to execute the content of
file.
 To execute the script we tell the interpreter the name of the file. The script will then be
executed until it reaches the end of the code and produce the desire output.
 The python script names are always ends with .py extension.
 In script mode, python does not display the result automatically.
 In order to see output from a script. The print statement is used.
 There are several ways to start the interpreter to evaluate the script file.

a. Explicitly from the command line.


b. Implicitly from the command line.
a. Explicitly from the command line

 The script name is provided as an argument while running python.

Hello1.py
 >>> python hello1.py
 Python prompt
Print(‘Hello world !’)
 Command to run
 Python script

 Output
Hello World!
b. Implicitly from the command line.

 In this case use either the GNU/Linux shell command or depend on the file association in windows.
 For Example:

 #!/usr/bin/python
Print(“Hello World !”)

It is assumed that the interpreter is now available inside /usr/bin directory. With the location of the interpreter the code
will run differently but produces the same result.
Steps in interpreting a python program

 The interpreter reads a python statement also called the python source code and verifies
that it is well formed.
 As soon as the interpreter encounter such as error. It halts translation with an error
message.
 The interpreter then translates in to an equivalent form in a low-level language is called
byte code.
 This byte code is next send to another software component called the python virtual
machine (PVM) where it executed if another error occurs during this step execution halts
with an error message.
Syntax Error
Python Code Syntax checker and
Messages
Translator

Byte Code
User Inputs
Python Virtual Machine
(PVM)
Other error
Messages

Program Output
Building Blocks of Algorithm
 Instruction / Statements
 State
 Control Flow
 Functions
Instruction / Statements
Instruction/Statements

 It is an instruction written in a high-level language that commands the computer to


perform a specified action.
 A program written in such a language is formed by a sequence of one or more statements
 A statement may have internal components (eg: expression)
 Many languages makes the distinction between statements and statement within the
definitions parts
 A distinction can also be made between simple and compound statements.
Kinds of Statements

The following are the major generic kinds of statements.


1. Simple Statements
2. Compound Statements
1.Simple Statements
 Assignment Statement:
 For example: A:=A+5
 Goto Statement:
 Sytax : goto LABEL;
 For example: goto next;
 Return Statement:
 For example Return 5;
 Call Statement:
 For example function()
2.Compound Statements

 Block Statement:
 For Example:
Begin

------

------

End

 do-loop Statement:
 For Example
do
-------
While(i>10)
 For-loop Statement:
 For Example:
for ( …)
{
------
------
}
 If-statement:
 For Example:
if (condition)
{
}
 Else Statement:
 For Example:
if (condition)
{
}
else
{
}
 Switch Statement:
 For Example:
switch(c)
{
case ‘a’:
alert();
break;
case ‘q’:
quit()
break;
default:
close();
break;
}
 While Loop Statement:
 For example:
while (condition)
{
}
State
State

 A state is associated with processing information, data is read from an input source or
device, written to an output sink or device.
 The state is stored in a data structure.
 A state is the result of a test or condition – either TRUE or FALSE.
Control Flow
Control Flow

 A control flow statement is a statement that choice has been made for the execution of
result.
Condition

Action 1

Action 2

Action 3
There are 2 types of Control Flow

 Sequence Control Structure.


 Selection Control Structure.
Sequence Control Structure

 Sequence Control Structure is used to perform the action one after another.
 For Example:
 It performs process A and then performs process B and so on.

Algorithm Pseudo Code Flow Chart

Step 1:Start Process 1 Process 1


Step 2: Process 1 .
Step 3: Process 2 . Process 2
Step 4: Process 3 Process 2
Step 5: Stop .
.
Process 3 Process 3
Selection Control Statement

 Selection Control Statement are otherwise called as Decision Structure.


 It allow the program to make choice between two alternate paths whether it is true or false.
1. If then Structure.
2. If then …. Else structure.
1.If then Structure

 This structure makes a choice between two process.


 If the condition is true it performs the process. If the condition is false it skips over the process.

Flow Chart

YES
Pseudocode IF
IF condition THEN conditi
Process 1 on


ENDIF Process NO
2.If then …. Else structure.

 In this structure if the condition is true it executes process 1 else if the condition is false it executes process
2.
 In this either the process 1 or process 2 get executed depending on the condition.

Flow Chart
Pseudo Code Yes
IF condition THEN If No
process 1 conditi
. on
.
ELSE
process 2 Process 1 Process 2
.
.
ENDIF
Iteration

 Iteration is a type of control flow statement.


 Iteration is used in computer programs to repeat a set of instruction.
 There are 2 types of iteration
 Count Controlled Iteration
 Condition Controlled Iteration

1. Count Controlled Iteration will repeat a set of instructions for specific number of times.
2. Condition Controlled Iteration will repeat a set of instruction until a specific condition is met.
Function
Function

 Any complex problem will become simpler if the problem is broken down into smaller and
the smaller problems are solved
 Solution to the smaller problem.
 Used for solving the complex and bigger problems.
 For Example:
The online shopping system can have several lines of program. The entire problem can be
solved by subdivided into smaller functions. The functions are otherwise called as Modules.
 Advantages
Writing the function could increase

 Readability.
 Efficiency.
 For examples:
Consider the ONLINE SHOPPING SYSTEM. It include following function name.

Product Add to Cart

Listing Change

Buy Check
Values and Types

A value is one of the fundamental things a program works with, like a


letter or a number. These values belongs to different types

For example: 1, 2 and “Hello world”


Types

A data type is a category for values and every value belong to exactly one data type.
There are 5 basic types of values. They are listed below :

1. Integer
2. Float
3. Boolean
4. String
5. List
1.Integers

 It is used to store numeric values.


 An integer is a number that can be written without a fractional component( without any
decimal point).
 The most common data types in python are listed below.

For example:
 Integer -2, -1, 0 , 1 , 2 …………
For example

>>> 1+1
2
>>> a=4
>>>type(a)

Type ‘int’
2.Float

 The float is a data type used to number with decimal point

For example:
>>>a=2.34
>>>b=3.5
>>>c=a+b
>>>print (c)
>>> type (c)

Type ‘float’
3.Boolean

 Boolean is a data type.


 A Boolean variable can take only two values, TRUE or FALSE.
 The main of this type is in logical expressions.

For example:

>>>a=True
>>>b=30 > 45 # b gets the value of FALSE
>>>type (b)

type `bool’
4.strings

 String are the sequence of character represented within quotation marks.


 It allows either pairs of single or double quotes.
 The substring access is possible through the slicing operator( [ ] or [:] )
 The string index 0 represents beginning of the string. Whereas, index -1 represents ending
of the string.

For Example
str=‘Hello world!’ #str – string variable assigned with a value.
Operators String

 The concatenation string with the “+” operator and create multiple concatenation copies of
a string with the “*”
Escape characters

 An escape character consists of blackslash (\)


 For Example:
\’ – single quote
\” - double quote
\t – tab
\n – new line
\\ - Backslash
Code Comment Result
print str # print complete string Hello world!
print str[0] # print first character of the H
string
print str[-1] # prints last character of the !
string
print str[1:5] #print character starting from Ello
index 1 to 4.
print str[2:] #prints string starting at index llo world!
2 till end of the string
print str*2 # asterisk (*) is the repetition Hello world! Hello world!
operator
print str+ ”hai” # print concatenated string Hello world! Hai
5.List

 List are the most significant compound data types contain elements of various types.
 A list can hold items of different data types.
 The list is enclosed by square brackets [ ] where the items are separated by commas like
string data type, the list values can be accessed using the slice operator ( [ ] or [:]).
 The index 0 represents beginning of the list whereas, index -1 represents ending of the list.
For examples

List1 = [‘abcd’ , 324, 3.2, ‘python’ , 3.14]

List2 = [234, ‘xyz’]


List Index

 We can use the index operator [ ] to access an item in a list. Index start from 0
 For example: if we have 5 element then index will start from 0 to 4
 Trying to access an element other that this will raise an index error.
 The index must be of integer. We can’t use float.
Negative Indexing

 Python allow negative indexing for its sequences. The index of -2 refers to the second last
item
Code Comment Result
print list1 # prints complete list abcd 324 3.2 python 3.14

print list1[0] # print first element of the List1 abcd

print list1[-1] # prints last character of the list 3.14

print list1[1:3] # prints the elements from index 1 to 2 324, 3.2

print list1[2:] # prints list starting at index 2 till end 324, 3.2, ‘python’
of the list

print list2*2 # asterisk(*) is the repetition operator 234, ‘xyz’ 234, ‘xyz’

print list1 + list2 # prints concatenated lists ‘abcd’ , 324, 3.2, ‘python’ , 3.14. 234,
‘xyz’
Notation of Algorithm
• Pseudo Code
• Flow Chart
• Programming language
1.Pseudocodes

 Pseudo code is not a real programming code written in English but it models and even look like
programming codes.
 Pseudo code comes from two words. Pseudo and code pseudo means imitation of false and code refer to
instruction written in programming languages
 It is a way of describing an algorithm without using any specific programming language related notation.
 It cannot be compiled or executed
 It is written in natural language such as English etc.
 It is used to concentration on algorithm
Keywords used in Pseudo Codes

 Pseudo code uses some keywords to denote programming processes. They are:
 Input : READ. OBTAIN. GET. PROMPT
 Output: PRINT. DISPLAY. SHOW
 Compute: COMPUTE, CALCULATE, DETERMINE
 Initialize: SET, INIT
 Add one: INCREMENT, BUMP
Rules of Pseudo Code

 Do not include data declaration in Pseudo code.


 Avoid words related to the kind of Computer Language.
 Start with an algorithm and phrase it using words that are easily converted into computer
instruction.
Examples

A pseudo code to add two numbers and display the results

READ num1, num2


result = num1+num2
WRITE result
Basic Guidelines for Writing Pseudocode

a. Write only one statement per line.


b. Capitalize Initial Keyword.
c. Indent to show hierarchy.
d. End multiline structure.
e. Keep statement language independent.
1. Write only one statement per line

 Each statement in your pseudo code should express only one action for the computer.
 For example:
READ num1 , num 2

The above line or Statement denoted the computer should read the
input for num1 and num 2
2. Capitalize Initial Keyword

 The keywords should be written in Capital Letter.


 For example
 READ a
 WRITE a

In the above example READ and WRITE are written in capital letter.
3. Indent to show hierarchy.

 The process of showing the boundaries of the structure.


 Sequence
It keeps the statement to be sequence. One step after another one
 Selection
The selection of statement is performed based on the condition.
 Looping
The steps that need to be repeated again and again.
For examples

IF a>b THEN
print a
ELSE
print b
4. End multiline structure.

 Each structure must be ended properly

 For example
IF condition THEN

ENDIF

In the above example the if statement has end properly “ENDIF”


5. Keep statement language independent

 Write in the language which is more comfortable with you.


 For example
English
French
Etc.
Advantages

 Can be done easily on a word processor (MS word).


 Easily modified.
 Implements structured concepts well.
 It is simple because it uses English-like structure.
 No special symbol are used.
 No special syntax is used.
 It is very easy to translate its statement to the high level programming language
( likes C, C++, etc)
Disadvantages

 It is not visual
 There is no standard. So that the pseudo codes get vary from company to company for same problem. (Eg:
add of two numbers.)
 Cannot be compiled or Executed.
FLOW CHART
Flow Chart

 Flow chart is a diagrammatic representation of an algorithm.


 The operation are showing in various kinds of boxes and there is order by connecting with
arrows.
 Flow chart are used in designing a process of program.
 Flow chart is very helpful in writing program and explaining program to others.
 Flow chart makes us to understand the problem unambiguously (clear)
 It is often used by programmer.
Symbol Purpose Description
Terminal ( Stop/Start) Representation start and
end of flowchart
Input / Output Representation Input and
Output Operation
Processing Represents arithmetic
operations and data –
manipulations
Decision Representation the
decision making operation
in which there are two
alternative TRUE and
FALSE
On-page Connector Used to join different flow
line
Predefined process / Represent a group of
function statements one processing
task and for function call.
Flow Line Indicates the flow of logic
by connecting symbols
Example
START

READ num1
and num2

SUM = num1 + num2

Display SUM

STOP
Basic Guide Lines for preparing flow chart

 In flow chart should be clear, neat and easy to follow.


 The usual direction of the flow of a procedure from top and bottom or left to right.
 Only one flow should be come out from the process.

 Only one flow should enter a decision symbol
Process Process

Conditi
on
 Only one flow line is used in START and STOP symbol.
START
STOP

 Validity of the flow chart can be tested by passing through simple test data.
Rules

 The standard symbols should only be used.


 The arrow heads in the flow chart represent the direction of flow of control in the problem.
 The direction flow usual from top to bottom or left to right.
 The flow lines should not be cross each other.
 Keep the flowchart as simple as possible.
 Words used in the flow chart should be easy to understand.
 If a new page is needed for flowchart then use connectors for better representation
Advantages

a. It is easy to understand.
b. A problem can be analyzed easily with flowchart.
c. It gives clear idea of a program.
d. It acts as a guide during the program development.
e. It helps to clear the error in coding.
f. It helps in maintenance of code.
Disadvantages

 It cannot be prepared for difficult program.


 Alternations and modification cannot be done easily.
 It is not typed so its preparation is little difficult.
Programming Language
Programming Language:

 A computer is the ideal machine to execute computational algorithm because.


 The computer can perform arithmetic operation.
 It can also perform an operation only when some condition is satisfied.
Problems

 We have to tell the computer what steps to do in machine language.


 Human are not good in machine languages.
 So we have developed specialized languages to instruct a computer.
 The specialized languages are called as High Level Programming Languages.
Types of languages used in computer
programming
1. Machine Language.
2. High Level Programming Language.
1.Machine Language

 The machine Language consists of binary numbers ( 0’s or 1’s) that encode instructions for
the computer.
 Every computer has its own machine language
 For Example
10110101
10101111
01010110
10110111
Assembler Language or Low level
programming language
 An assembler language consists of (English like) Mnemonics.
 There is one mnemonic for each machine instruction of the computer.
 For Example
Start
ADD X , Y
SUB X ,Y
-----
------
End
2.High level Programming Language

 A high level programming language allow the programmer to write sentences in this
language which can be easily translated into machine instructions.
 The sentence written in a high level programming language ( c , c++ and java) are
called statements.
main ()
{
For examples If (x > y)
{
Max=x
}
Else
{
max=y
}
---
---
}
Some well-known programming languages

 Fortran
 Cobol
 C
 C++
 Java
 C#
 Perl
 Python
Way of Execution
There are two different way of execution.

Interpreter Compiler

1. Translates the program one 1. Scans the entire Program and


statement at a time translate into machine code

2.It takes less amount of time for 2. It takes large amount of time for
execution execution when compare to
interpreter
3. No intermediate object code is 3. It generates intermediate object
generated. code.
4. Programming languages like 4. Programming language like C,
python, ruby use interpreters. C++ use compilers.
Variables
Variables

 While creating a variable memory space is reserved in memory to store values.


 In other words a variable in a program gives data in the computer to work on.
 Variable is an identifier that refer to a value.

examples
 >>> msg = ‘hello world !’
 >>> n=12
 >>> pi = 3.14
 The first statement creates a variable, msg and assign ‘Hello world!’ to it.
 The second statement creates a variable n assign 12 to it.
 The third statement creates a variable pi assign 3.14 to it.
 Variable names can contain both letter and number.
 But do not start with a number.
 The underscore character ( _ ) can be used in variable names.
Rules of defining identifiers

 Identifiers can be a combination of lowercase letter ( a to z) or uppercase letter ( A to Z )


or digits ( 0 or 9) or an underscore ( _ )
 Identifiers cannot start with the digit.
 Keywords cannot be used as identifiers and identifiers can be any length.
 No special symbol like ! , @ , # , $ etc.
 Valid identifiers: sum , total, average , _ab_ , add_1 , x1
 Invalid identifiers: 1x ,char ,x+y
Keywords

 In addition to variables, python has 31 keywords.


 Keywords are reserved words that cannot be used as ordinary identifiers.
 All the keywords except True, False and None are in lowercase and they must be written
as it is .

and del from not while as elif global or

with assert else if pass yield break except import

print class exec raise in continue is finally return


Re-declare a variable

 In the re-declare the variable even after you assign a value to it once. The variable can assign a

another one value. Here variable initialize to C=0. Later reassign the variable C to value

“Welcome”

#python program
C=0
print C
C=“Welcome”
print C
OUTPUT
0
Welcome.
Concatenate variable

 we can concatenate different data types like string and number together.

For example:
 It will concatenate “world” with number “88”.
a=“cse”
b=2018
print a+str(b)
it can concatenate both “cse”+str(“2018”)
OUTPUT
cse2018
Local & Global variables

 Variable “f” is global declared and is assigned value 101 which is printed in output.
 Variable f is again declared in function and assumes local variables. And it assign the
value “I am learning python” which is printed as an output.
 Once the function call is over, the local variable f is destroyed .
For examples

f=101
print (f)
def somefunction():
f=“god is great”
print (f)
somefunction()
print (f)
OUTPUT
101
god is great
101
Delete a Variable

 The variable can be delete using the command del “variable name”.
 For example
#declare a variable and initialize it.
b=102
print b
del b
print b
OUTPUT
NameError: name ‘b’ is not defined.
Swap Variables

 Python swap values in a single line and this applies to all objects in python.
 Syntax

var1, var2 = var2, var1


 For examples
x=10
y=20
print (x)
x, y = y, x
print (x)
print (y)
Algorithmic Problem Solving

05/28/2025
Algorithmic Problem Solving

 Algorithm are procedural solutions to problems.


 These solutions are not answers but specific instruction for getting answer.

05/28/2025
05/28/2025
 The steps are listed below.
1. Understanding the problem.
2. Ascertaining the capabilities of the computational Device.
3. Choosing between exact and approximate problem solving.
4. Deciding on appropriate Data Structures.
5. Algorithm design techniques
6. Methods of specifying an algorithm.
7. Proving an algorithm correctness.
8. Analyzing an algorithm.
9. Coding an algorithm

05/28/2025
1.Understanding the problem.

 Before designing an algorithm you have to understand complexity of the given problem.
 Read the problems description carefully and ask question if there are any doubt about the
problem do a few small examples by hand.

05/28/2025
2.Ascertaining the capabilities of the computational Device.

 Once you understand the complexity of the problem then you should ascertain the
capabilities of the computational device.
 Sequential algorithm : Instructions are executed one after another one operation at a
time.
 Parallel Algorithm: Some newer computer can execute operation concurrently i.e..
Parallel

05/28/2025
3.Choosing between exact and approximate problem solving.

 The next principal decision is to choose how to solve the problem.


 Solving the problem exactly is called an exact algorithm.
 Solving it approximately is called an approximately algorithm.

05/28/2025
4.Deciding on appropriate Data Structures.

 In object oriented programming data structure remain an important thing for both design
and analysis of algorithm.
 In computer science a data structure is a particular way of organizing data in a computer.
So that it can be used efficiently.
 ALGORITHM + DATA STRUCTURE = Programs

05/28/2025
5.Algorithm design techniques

 An algorithm design techniques is a general approach to solve problem.


 There are variety of problem from different area of computing.
 Algorithm design techniques makes it possible to classify algorithm according to an
underlying design idea. Therefore they can both categorize and study algorithm.

05/28/2025
6.Methods of specifying an algorithm.

 Once an algorithm is designed you need to specify it in some fashion

 a step by step form.

These are two options that are widely


used now a days.
05/28/2025
 Pseudo code: Pseudo code is a mixture of a natural language and programming language.
 Usually pseudo code are written in natural language (like English ).

 Flow Chart: Flow chart is another method of expressing an algorithm by collection of


connected geometric shapes.

05/28/2025
7.Proving an algorithm correctness.

 Once an algorithm has been specified it has to be proved for its correctness
 A common technique for proving correctness is to use mathematical induction.

05/28/2025
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.

05/28/2025
9.Coding an algorithm

 Most algorithm are implemented as computer programs.


 As a practical matter the validity of programs is still established by testing.
 Testing of computer program is an art rather than a science. But it check whether it solve
the problem.

05/28/2025
Expressions and Statements
Expressions

 An expression is a combination of value, variables and operation . The value and a


variable itself considered as an expression.
 For example:
17 # expression
X # expression
X +17 # expression
 The evaluation of an expression produce a value. And the expression can appear on the
right hand side of assignment statements.
 A value all by itself is a simple expression
 For example
>>> 26
26
>>>x=10
>>>x
10
 Evaluating an expression is not quite the same thing as printing value.
line = “god is great”
print (line)
output
god is great

 In case of string that means it includes the quotation marks. But the print statement prints
the value of the expression.
 Without the quotation marks which print is the contents of the string.

For example:
x=“sachin”
print(x)
print(“x”)
Statements
Statements

 A statement is an instruction that the python interpreter can execute.


 We have seen two kinds of statements

Print Statement
Assignment Statement.
 When you type a statement on the command line, python execute and display the result. If
there is one. The result of a print statement is a value.
 Assignment statement don’t produce a result.
 A script usually contains a sequence of statements. If there is more than one statement, the
result appear one at a time as the statements execute.
For example

print (“1”)
x=2
print (x)
OUTPUT
1
2
Multi-Line Statement

 Python allows the use of line continuation character ( \) to denote that the line should
continue.
 This is explicit line continuation.
 For example:
Total=mark1+\
mark2+\
mark3
 But the statements contained within [ ] { } or ( ) brackets do not need to use line
continuation characters.
For example

Item = [ ‘item1’ ,
‘item2’ ,
’item3’ ]
 This is implicitly continuation.
 Same is the case with [ ] and { }.

For example
Color=[ “red” ,
“blue” ,
“green”]
Print(Color)
Output
[‘red’ ‘blue’ ‘green’]
We could also put multiple statement in a single line using semicolons as follows

For example:
a=1;b=3;c=4
Simple Strategies for
Developing algorithm
Simple Strategies for Developing algorithm

 Iteration and recursion are key computer science techniques used in creating algorithm and
developing software.
 An iterative function is one that loops to repeat some part of the code.
 A recursive function is one that call itself again to repeat the code.
Iteration

 Iterative programs are programs that follow a path from the starting instruction till the end
of the algorithm.
 In iterative program the loop get repeated to achieve the desired the result.
 The basic structure of an iterative program is
for val in sequence:
body of for loop.
Step to develop an iterative program

 Define Problem:

The problem that needs an iteration has to be identified and defined.


 Initial Conditions:
The initialize has help to start the iteration.
 Define loop invariants:
The variable that controls the number of iteration
 Define Step:
The step that are to be repeated must be defined.
 Define Exit Condition:
The exit condition defines when iteration should get stopped.
For examples

 Sum of digits.
Recursive Iterative

1. Repetition is achieved through repeated function 1. Iteration is explicitly a repetition structure.


calls

2. Recursion terminates when a base case is 2. Iteration terminates when the loop continuation
recognized. test becomes false

3. Recursion cause another copy of the function and 3. Iteration normally occurs within a loop so the
hence a considerable memory space is occupied extra memory assignment is omitted.
Recursion

 In a recursive algorithm the algorithm calls itself with “ smaller” input values.
 The recursive programs require more memory and computation compared with iterative
algorithm . But they are simpler and a natural way of solving a problem.
 In a recursive algorithm the condition is verified during the execution of the algorithm and
not at the end as in iterative algorithm.
For examples

 Towers of Hanoi.

 Algorithm
 Pseudo code.
 Flow chart
Advantages of Recursive functions

 Recursion can produce simpler, more natural solution to the problem.


 It is written with less number of statements
 It requires few variables which makes program clean.
 It is useful for branching processes.
Tuple assignment
Tuple assignment

 Tuples is a sequence of item of any type.


 Syntactically tuple is a comma separated list of values.
 tuples are enclosed within the parenthesis.
 Tuples can be thought of as read-only lists.

 For example: the tuples can be created as follow


#python program
student=(“aaa”,96,”sachin”)
print(student)
print(student[0])
print(student[-1])
Output
(‘aaa’,96,’sachin’)
aaa
sachin

 The main difference between list and tuples are:


 Lists are enclosed in bracket ( [ ] ) and their element and size can be changed.
 While tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
 Python has a very powerful tuple assignment feature that allows a tuple of variable on the left of an
assignment to be assigned values from a tuple on the right of the assignment.

For example
#python program
(a,b)=(12, 32)
print (a)
(a,b) = (b,a)
print (a)
Output
12
32
Tuple assignment

 (a ,b) = (3 , 4)
 The above line has the two assignment statements all on one easy line.
 Once in a while it is useful to swap the value of two variables , with conventional
assignment statement , we have to use a temporary variable.
For examples

to swap the value of a and b

temp = a
a=b
b=temp
Tuple assignment solves this problem neatly:
(a ,b) = (b ,a)
 The left side is a tuple of variables; the right side is a tuple of values. Each value is
assigned to its respective variables.
 All the expression on the right side are evaluated before any of the assignments.
 This features makes tuple assignment quite versatile.
 Naturally the number of variables on the left and the number of values on the right have to
be the same.
Comments

 Comments are the kind of statement that are written in the program for understanding
program
 By the comment statements it is possible to understand what exactly the program is doing.
 In the python we use the hash (#) symbol to start writing a comment.
 It extends up to the newline character.
 Python interpreter ignores comment.
For example

#python program
print(“i love my country”) #print the word “i love my country”
print(“india”) #print the word “india”
a=1 # the variable ‘a’ has assign the value of 1
print(a)
Output
i love my country
india
1
 If we have comments that extends multiple lines one way of doing it is to use hash ( # ) in
the beginning of each line.
 For example
#this is
#another example
#of comment statement
Comments

 Comments are the non-executable statements explain what the program does. For large
programs if often difficult to understand what is does.
 The comment can be added in the program code with the symbol #.
 For Examples

print “hello world !” # print the message hello world! comment


v=5 # creates the variable v and assign the value 5; comment.
Multi-line Comment Statement

 A comment is a piece of program text that the interpreter ignores but provides useful
documentation to programmers.
 Alternatively we can use triple single ( ‘ ‘ ‘ ) or triple double quotes ( “ “ “ ) at the start and
end of a multiple-line comment.
 The author of a program can include his/her name and a brief statement about the purpose
of the program at the beginning of the program file.
 This type of comment is called as a docstring.
 SYNTAX
# Single line comment statement
‘ ‘ ‘ multi-line comment
Statement 1
Statement 2 ‘ ‘ ‘
Insert a CARD in a list of
sorted cards
Insertion Sort
The Idea of the insertion sort is similar to the Idea
of sorting the Playing cards .
1 3 4 5 6
1 3 4 5 6
1 3 4 5 6

Now Insert the number 2

2
1 2 3 4 5 6
Step 1: Start
Step 2: read the value from an array A [Start, ... End]
Step 3: read the value of keycard
Step 4:for i in range 1 to length(A)
Step 4.1:j=i-1
Step 4.2:while j>=0 and keycard < A[j]:
Step 4.3:A[j+1] = A[j]
Step 4.4:j=j-1
Step 4.5:A[j-1]=keycard
Step 5:Stop
Guess an integer number in a
range
START
Step 1: Start
Click icon to add picture
Step 2: num=random.random(1,10)
Create a num random
Step 3: while True: number 1 -10
Step 4: print("Guess a number between 1 and 10")
Read guess number from
Step 5:read the value of I user
Step 6: if (i==num)
Step 6.1: print("you have guessed correct number !!") Is guess Number is
> num higher
Step 6.2: break
Step 7: else if i < num:
Is
Step 7.1: print("number is lower enter higher") guess
Number is lower
Step 8: else if i > num: < num

Step 8.1: print("number is higher enter lower") Is


Step 9: Endif guess
= num
Step 10: stop

Stop
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
Target data found

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
Best Case:
1 comparison

Best Case: match with the first item

7 12 5 22 13 32
target = 7
Worst Case:
N comparisons

Worst Case: match with the last item (or no match)

7 12 5 22 13 32
target = 32
Tower of Hanoi
It is the best example of recursive algorithm
Introduction

 Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings is as depicted
 These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one.
 There are other variations of the puzzle where the number of disks increase, but the tower
count remains the same.
Rules

 The mission is to move all the disks to some another tower without violating the sequence
of arrangement.
 A few rules to be followed for Tower of Hanoi are

 Only one disk can be moved at a time.


 Only the "top" disk can be removed.
 No large disk can sit over a small disk.
Steps to solve the Tower of Hanoi
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Steps involved in tower of hanoi

 Step 1 − Move n-1 disks from source to aux


 Step 2 − Move nth disk from source to dest
 Step 3 − Move n-1 disks from aux to dest
Algorithm

Step 1: Start
Step 2:Procedure Hanoi(disk, source, dest, aux)
Step 3: IF disk == 1, THEN
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:END IF
Step 6:END Procedure
Step 7: Stop
Pseudocode

Procedure Hanoi(disk, source, dest, aux)


IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest)
move disk from source to dest
Hanoi(disk - 1, aux, dest, source)
END IF

END Procedure
Flow Chart

You might also like