Problem Solving Techniques in Python
Problem Solving Techniques in Python
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a
correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
1. ALGORITHM
The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem,
some of these may provide more accurate results than others, and such algorithms may be suitable
2
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
Read the value of ‘a’ //This is input statement
Calculate c=a+b //This is assignment statement
Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to
run in program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
3
3. Read b
4. If a>b then
4.1. Print a is greater
else
4.2. Print b is greater
5. Stop
4.1. Print i
5. Stop
Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function
4
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return
2. NOTATIONS OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language, Pseudo
code, flowcharts and programming languages. Natural language tends to be verbose and
ambiguous. Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among each
others in problem solving to represent technical facts, created to facilitate the best result for a program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer
program or algorithm. It uses the basic structure of a normal programming language, but is intended
for human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions written
in programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules.
The pseudocode is written in normal English language which cannot be understood by the computer.
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
5
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
Advantages of Pseudocode
Can be done easily on a word processor
Easily modified
Implements structured concepts well
It can be written easily
It can be read and understood easily
Converting pseudocode to programming language is easy as compared with
flowchart
Disadvantages of Pseudocode
It is not visual
There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
[Link] Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
6
5. Flow lines Arrow lines Represents the sequence
of steps and direction of
flow. Used to connect
symbols.
7
6. Connector Circle A connector symbol is
represented by a circle and
a letter or digit is placed in
the circle to specify the
link. This symbol is
used to
connect flowcharts.
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various
purposes.
Efficient Coding
8
The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It
helps the programmer to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
Control Structures using flowcharts and Pseudocode
Sequence Structure
Pseudocode Flow Chart
General Structure
Process 1
…. Process 1
Process 2
…
Process 2
Process 3
Process 3
Example
READ a
Start
READ b
Result c=a+b
PRINT c a=10,b=20
9
Conditional Structure
Conditional structure is used to check the condition. It will be having two outputs only (True or False)
IF and IF…ELSE are the conditional structures used in Python language.
CASE is the structure used to select multi way selection control. It is not supported in Python.
Process 1
Process 2
Example
READ a
READ b Start
IF a>b THEN
PRINT a is greater a=10,b=20
Print a is greater
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2
Process 2
Example
10
READ a Start
READ b
IF a>b THEN
a=10,b=20
PRINT a is greater
Yes if (a>b)
Print a is greater
No
Print b is greater
Stop
Yes
Body of the loop
Example
DO…WHILE is exit checked loop, so the loop will be executed at least once.
11
INITIALIZE a=1 Start
Yes
Stop
Print a
a=a+1
Programming Language
A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
Programming languages are also used to organize the computation
Using Programming language we can solve different problems
To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
Low – level or Machine Language
Intermediate or Assembly Language
High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions and
variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
12
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are more or less independent of a particular type of
computer. Such languages are considered high-level because they are closer to human languages and
further from machine languages. Ultimately, programs written in a high-level language must be translated into
machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.
Figure
g : Interpreter
Compiled Programming Languages
Compile is to transform a program written in a high-level programming language from source
code into object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.
Figure: Compiler
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it as whole
into machine code
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower comparatively faster
No intermediate object code is generated, Generates intermediate object code which
hence are memory efficient further requires linking, hence requires more
memory
Continues translating the program until first It generates the error message only after
error is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java
If the instructions are executed one after another, it is called sequential algorithm
Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as the
algorithm’s implementation.
Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively. But
in order to show that an algorithm is incorrect, you need just one instance of its input for which
the algorithm fails.
Analyzing an Algorithm
1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
14
2. simplicity.
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several inputs
and then analyzing the results obtained.
15
Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some specified condition has
beensatisfied.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
16
FLOW CHART
Main function:
BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
17
INTRODUCTION TO OOPs:
What is OOP?
OOP is a programming approach where everything is represented as objects.
Objects contain:
o Data → attributes/properties
o Functions → methods/behaviors
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
18
Class
class ClassName:
# Statement-1
.
.
# Statement-N
Objects
class employee():
def __init__(self,name,age,id,salary): //creating a function
[Link] = name // self is an instance of a class
[Link] = age
[Link] = salary
19
[Link] = id
emp1 = employee("harshit",22,1000,1234) //creating objects
emp2 = employee("arjun",23,2000,2234)
print(emp1.__dict__)//Prints dictionary
Explanation
• ’emp1′ and ’emp2′ are the objects that are instantiated against the class ’employee’.
• Here, the word (__dict__) is a “dictionary” which prints all the values of object ‘emp1’
against the given parameter (name, age, salary).
• (__init__) acts like a constructor that is invoked whenever an object is created.
Methods:
class Student:
20
# Another instance method
def is_adult(self):
if [Link] >= 18:
return True
else:
return False
# Creating objects
student1 = Student("Akshara", 19)
student2 = Student("Rahul", 16)
# Calling methods
[Link]() # Output: Hi, my name is Akshara and I am 19 years old.
[Link]() # Output: Hi, my name is Rahul and I am 16 years old.
# Checking if adult
print(student1.is_adult()) # Output: True
print(student2.is_adult()) # Output: False
INHERITANCE:
It allows code reusability, extension, and organization by enabling one class to use
features of another without rewriting code.
21
Add its own new properties & methods.
Override parent’s methods (polymorphism).
Types of Inheritance
Single Inheritance
Multilevel Inheritance
Inheritance occurs across multiple levels (a child becomes a parent for another child).
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a child
and a grandfather.
Multilevel Inheritance
23
class childemployee1(employee)://First child class
def __init__(self,name,age,salary):
[Link] = name
[Link] = age
[Link] = salary
Hierarchical Inheritance
class employee():
def __init__(self, name, age, salary): //Hierarchical Inheritance
[Link] = name
24
[Link] = age
[Link] = salary
class childemployee1(employee):
def __init__(self,name,age,salary):
[Link] = name
[Link] = age
[Link] = salary
class childemployee2(employee):
def __init__(self, name, age, salary):
[Link] = name
[Link] = age
[Link] = salary
emp1 = employee('harshit',22,1000)
emp2 = employee('arjun',23,2000)
print([Link])
print([Link])
Multiple Inheritance
25
Multiple Inheritance Example
class childemployee(employee1,employee2):
def __init__(self, name, age, salary,id):
[Link] = name
[Link] = age
[Link] = salary
[Link] = id
emp1 = employee1('harshit',22,1000)
emp2 = employee2('arjun',23,2000,1234)
print([Link])
print([Link])
Hybrid Inheritance
A combination of two or more types of inheritance.
(Often involves multiple + multilevel + hierarchical together.)
26
Polymorphism
What is Polymorphism?
Polymorphism means “many forms”.
In OOP, it allows objects to be treated as instances of their parent class rather than their actual
class. The main idea is that a single function or method can work in different ways depending
on the object it is acting upon.
o The decision about which method to call is made during compile time.
o The decision about which method to call is made at runtime depending on the
object.
1. Compile-time Polymorphism
Method Overloading
Same method name but different parameters (number, type, or order).
27
class Calculator:
# Adding 2 numbers
def add2(self, a, b):
return a + b
# Adding 3 numbers
def add3(self, a, b, c):
return a + b + c
2. Run-time Polymorphism
Method Overriding
When a child class has a method with the same name as the parent class, but it changes the
way it works.
Same method name (sound) but different output depending on the object.
29
2 MARKS
1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous do able steps that
can be systematically followed to produce a desired results for given input in the given amount
of time. In other word, an algorithm is a step by step procedure to solve a problem with finite
number of steps.
Algorithm Program
1. Systematic logical approach which is a It is exact code written for problem
well-defined, step-by-step procedure that following all the rules of the
allows a computer to solve a problem. programming language.
2. An algorithm is a finite number of clearly The program will accept the data to
described, unambiguous do able steps that perform computation.
can be systematically followed to produce
a desired results for given input in the Program=Algorithm + Data
given amount of time.
6. Write an algorithm to accept two numbers, compute the sum and print the result.
Step 1: Start
Step 2: Declare variables num1,num2 and sum,
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum
30
7. Differentiate between iteration and recursion.
11. Draw a flow chart to find whether the given number is leap year or not
31
Start
Read year
If
(year%4==0)
Stop
32