Problem Solving and Python Programming
Problem Solving and Python Programming
Python Programming
Objective
05/28/2025
How a software get developed ?
1.Planning
2.Designing
3.Programming (Coding)
4.Testing
5.Deployment
05/28/2025
What is programming ?
Programming involves creativity, analytical thinking, knowledge in the language in which coding or
the programming is done.
Definition
Example
Characteristic of algorithm
Qualities of an algorithm
Representation of algorithm
Advantages of algorithm
Disadvantages of algorithm
05/28/2025
Problem
Algorithm
05/28/2025
Definition
05/28/2025
Examples:
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
05/28/2025
Disadvantages of algorithm
05/28/2025
Python Interpreter and
Interactive
UNIT II
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
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
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.
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
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 is used to perform the action one after another.
For Example:
It performs process A and then performs process B and so on.
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
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.
Listing Change
Buy Check
Values and 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
For example:
Integer -2, -1, 0 , 1 , 2 …………
For example
>>> 1+1
2
>>> a=4
>>>type(a)
Type ‘int’
2.Float
For example:
>>>a=2.34
>>>b=3.5
>>>c=a+b
>>>print (c)
>>> type (c)
Type ‘float’
3.Boolean
For example:
>>>a=True
>>>b=30 > 45 # b gets the value of FALSE
>>>type (b)
type `bool’
4.strings
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
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
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[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
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
In the above example READ and WRITE are written in capital letter.
3. Indent to show hierarchy.
IF a>b THEN
print a
ELSE
print b
4. End multiline structure.
For example
IF condition THEN
ENDIF
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
READ num1
and num2
Display SUM
STOP
Basic Guide Lines for preparing flow chart
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
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
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
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
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
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
05/28/2025
Algorithmic Problem Solving
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.
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
05/28/2025
6.Methods of specifying an algorithm.
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.
05/28/2025
9.Coding an algorithm
05/28/2025
Expressions and Statements
Expressions
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
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:
Sum of digits.
Recursive Iterative
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
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
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
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
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
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
7 12 5 22 13 32
target = 7
Worst Case:
N comparisons
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
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
END Procedure
Flow Chart