0% found this document useful (0 votes)
14 views33 pages

Problem Solving Techniques in Python

The document provides an introduction to problem solving and Python programming, focusing on the systematic approach to defining problems and creating solutions through techniques such as algorithms, flowcharts, and pseudocode. It outlines the qualities of good algorithms, building blocks, control flow structures, and the advantages and disadvantages of pseudocode and flowcharts. Additionally, it discusses programming languages, their types, and the need for them in organizing computations and improving program efficiency.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views33 pages

Problem Solving Techniques in Python

The document provides an introduction to problem solving and Python programming, focusing on the systematic approach to defining problems and creating solutions through techniques such as algorithms, flowcharts, and pseudocode. It outlines the qualities of good algorithms, building blocks, control flow structures, and the advantages and disadvantages of pseudocode and flowcharts. Additionally, it discusses programming languages, their types, and the need for them in organizing computations and improving program efficiency.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NOTES OF LESSON

22UIT103 - PROBLEM SOLVING


AND PYTHON PROGRAMMING
UNIT I

INTRODUCTION TO COMPUTING AND OBJECT ORIENTED


CONCEPT

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

It is defined as a sequence of instructions that describe a method for solving a problem.


In other words it is a step by step procedure for solving a problem

 Should be written in simple English


 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.

Qualities of a good 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

Building Blocks of Algorithm


As algorithm is a part of the blue-print or plan for the computer program. An algorithm is
constructed using following blocks.
 Statements
 States
 Control flow
 Function

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

Sequential control flow:


The name suggests the sequential control structure is used to perform the action one after
another. Only one step is executed once. The logic is top to bottom approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection or Conditional control flow
Selection flow allows the program to make choice between two alternate paths based on
condition. It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two
numbers.
Example
Description: finding the greater number
1. Start
2. Read a

3
3. Read b
4. If a>b then
4.1. Print a is greater
else
4.2. Print b is greater
5. Stop

Repetition control flow


Repetition control flow means that one or more steps are performed repeatedly until some
condition is reached. This logic is used for producing loops in program logic when one one more
instructions may need to be executed several times or depending on condition.
Basic Structure:
Repeat untilCONDITIONis true
Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n

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

Algorithm for addition of two numbers using function


Main function()
Step 1: Start
Step 2:Call the function add()
Step 3: Stop
sub function add()
Step1:Functionstart

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

5. Keep statements language independent.


Pesudocode must never written or use any syntax of any programming language.

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.

2. Input/ Output Parallelogram Denotes either input or


symbol output operation.

3. Process symbol Rectangle Denotes the process to be


carried

4. Decision symbol Diamond Represents decision


making and branching

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.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
Only one flow line should come out from a process symbol.

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.

5. Only one flow line is used in conjunction with terminal symbol.

6. If flowchart becomes complex, it is better to use connector symbols to reduce the


number of flow lines.
7. Ensure that flowchart has logical start and stop.

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.

Pseudocode Flow Chart


General Structure
IF condition THEN
Process 1 if(condition)
ENDIF

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

Pseudocode Flow Chart


General Structure
IF condition THEN
Process 1
if(condition)
ELSE
Process 2
ENDIF Process 1

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

Iteration or Looping Structure


 Looping is generally used with WHILE or DO...WHILE or FOR loop.
 WHILE and FOR is entry checked loop

Pseudocode Flow Chart


General Structure
WHILE condition
Body of the loop No
ENDWHILE if(condition)

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

WHILE a<10 THEN


PRINT a
a=1
a=a+1
ENDWHILE
No
if (a<10)

Yes
Stop

Print a

a=a+1

o In python DO…WHILE is not supported.


o If the loop condition is true then the loop gets into infinite loop, which may lead to system
crash

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.

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP,Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python
Interpreted Programming Language:
Interpreter is a program that executes instructions written in a high-level language.
An interpreter reads the source code one instruction or one line at a time, converts this line into
machine code and executes it.

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

3. ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an


algorithm for the solution.

Understanding the Problem


 It is the process of finding the input of the problem that the algorithm solves.
 It is very important to specify exactly the set of inputs the algorith m needs to handle.
 A correct algorithm is not one that works most of the time, but one that works
Correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device

If the instructions are executed one after another, it is called sequential algorithm

Choosing between Exact and Approximate Problem Solving


 The next principal decision is to choose between solving the problem exactly or solving it
approximately.
 Based on this, the algorithms are classified as exact algorithm and approximation
algorithm.
 Data structure plays a vital role in designing and analysis the algorithms.
 Some of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance
 Algorithm+ Data structure=programs.

Algorithm Design Techniques


 An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving
problems algorithmically that is applicable to a variety of problems from different areas of
computing.
 Learning these techniques is of utmost importance for the following reasons.
 First, they provide guidance for designing algorithms for new problems,
Second, algorithms are the cornerstone of computer science.

Methods of Specifying an Algorithm


 Pseudocode is a mixture of a natural language and programming language-like constructs. Pseudocode
is usually more precise than natural language, and its usage often yields more succinct algorithm
[Link] the earlier days of computing, the dominant vehicle for specifying algorithms was a
flowchart, a method of expressing an algorithm by a collection of connected geometric shapes
containing descriptions of the algorithm’s steps.

 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.

 A common technique for proving correctness is to use mathematical induction because an


algorithm’s iterations provide a natural sequence of steps needed for such proofs.

 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.

4. Simple strategies for developing algorithm:


They are two commonly used strategies used in developing algorithm
1. Iteration
2. Recursion
Iteration
 The iteration is when a loop repeatedly executes till the controlling condition becomes false
 The iteration is applied to the set of instructions which we want to get repeatedly executed.
 Iteration includes initialization, condition, and execution of statement within loop and update
(increments and decrements) the control variable.
A sequence of statements is executed until a specified condition is true is called iterations.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
BEGIN
FOR( start-value to end-value) DO GET n
statement INITIALIZE i=1
... ENDFOR FOR (i<=n) DO
PRINT i
i=i+
1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
BEGIN
WHILE (condition) DO GET n
statement INITIALIZE i=1
... WHILE(i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END

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.

Algorithm for factorial of n numbers using recursion:

Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop

Sub function factorial(n):


Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

16
FLOW CHART

Pseudo code for factorial using recursion:

Main function:

BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN

Sub function factorial(n):

IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

17
INTRODUCTION TO OOPs:

What is Programming Paradigm?


A programming paradigm is a way of thinking and structuring code.
 Procedural Programming (C, Pascal): Program is divided into functions, focus is on
how to do.
 Object-Oriented Programming (OOPs) (C++, Java, Python, C#): Program is divided
into objects, focus is on what to do with data.

Object Oriented Programming is a fundamental concept in Python, empowering


developers to build modular, maintainable and scalable applications.
OOPs is a way of organizing code that uses objects and classes to represent real-world entities
and their behavior. In OOPs, object has attributes thing that has specific data and can perform
certain actions using methods.

What is OOP?
 OOP is a programming approach where everything is represented as objects.

 Objects contain:

o Data → attributes/properties

o Functions → methods/behaviors

 OOP helps in writing reusable, modular, and maintainable code.

OOP Concepts in Python


Python supports the core principles of object-oriented programming, which are the building
blocks for designing robust and reusable software. These are:
 Class

 Objects

 Polymorphism

 Encapsulation

 Inheritance

 Data Abstraction

18
Class

• A class is a collection of objects.


• A class contains the blueprints or the prototype from which the objects are being created.
• It is a logical entity that contains some attributes and methods.
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator.
Eg: [Link]

Class Definition Syntax:

class ClassName:
# Statement-1
.
.
# Statement-N

Objects

Objects are an instance of a class.


• It is an entity that has state and behavior.
• In a nutshell, it is an instance of a class that can access the data.
• Syntax: obj = class1()
• Here obj is the “object “ of class1.

Class and Object Example:

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:

• A special kind of function that is defined in a class definition.


• They are used to define the behaviors of an object.
• Inside a Class, we can define the following three types of methods
• Instance method: Used to access or modify the object attributes.
• Class method: Used to access or modify the class state.
• Static method: It is a general utility method that performs a task in
isolation.

Define a Class with Methods:

class Student:

# Constructor method to initialize attributes


def __init__(self, name, age):
[Link] = name
[Link] = age

# Instance method (belongs to the object)


def introduce(self):
print(f"Hi, my name is {[Link]} and I am {[Link]} years old.")

20
# Another instance method
def is_adult(self):
if [Link] >= 18:
return True
else:
return False

Create Objects and Call Methods

# 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:

Inheritance is an object-oriented programming (OOP) concept where a new class (called


the child class or derived class) acquires the properties (attributes) and behaviors
(methods) of an existing class (called the parent class or base class).

It allows code reusability, extension, and organization by enabling one class to use
features of another without rewriting code.

Parent/Base Class → the existing class whose features are inherited.


Child/Derived Class → the new class that inherits features from the parent.

Child class can:


 Use parent’s properties & methods.

21
 Add its own new properties & methods.
 Override parent’s methods (polymorphism).

Types of Inheritance

Single Inheritance

 A child class inherits from only one parent class.


Single inheritance enables a derived class to inherit properties from a single parent class,
thus enabling code reusability and the addition of new features to existing code.

Single Inheritance Example

class employee1()://This is a parent class


def __init__(self, name, age, salary):
[Link] = name
[Link] = age
[Link] = salary

class childemployee(employee1)://This is a child class


def __init__(self, name, age, salary,id):
[Link] = name
[Link] = age
[Link] = salary
22
[Link] = id
emp1 = employee1('harshit',22,1000)
print([Link])

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

Multilevel Inheritance Example

class employee()://Super class


def __init__(self,name,age,salary):
[Link] = name
[Link] = age
[Link] = salary

23
class childemployee1(employee)://First child class
def __init__(self,name,age,salary):
[Link] = name
[Link] = age
[Link] = salary

class childemployee2(childemployee1)://Second child class


def __init__(self, name, age, salary):
[Link] = name
[Link] = age
[Link] = salary
emp1 = employee('harshit',22,1000)
emp2 = childemployee1('arjun',23,2000)
print([Link])
print([Link])

Hierarchical Inheritance

One parent class has multiple child classes.


When more than one derived class are created from a single base this type of inheritance
is called hierarchical inheritance.

Hierarchical Inheritance Example

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

A child class inherits from more than one parent class.


When a class can be derived from more than one base class this type of inheritance is called
multiple inheritances. In multiple inheritances, all the features of the base classes are
inherited into the derived class.

25
Multiple Inheritance Example

class employee1()://Parent class


def __init__(self, name, age, salary):
[Link] = name
[Link] = age
[Link] = salary

class employee2()://Parent class


def __init__(self,name,age,salary,id):
[Link] = name
[Link] = age
[Link] = salary
[Link] = id

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.

Why is Polymorphism important?


 It increases flexibility and reusability of code.

 It allows the same method to behave differently for different classes.

 Helps in implementing dynamic method dispatch (deciding at runtime which method


to call).
Types of Polymorphism
1. Compile-time Polymorphism (Static Binding)
o Achieved through Method Overloading and Operator Overloading.

o The decision about which method to call is made during compile time.

2. Run-time Polymorphism (Dynamic Binding)


o Achieved through Method Overriding.

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

 The method name is the same → add


 It behaves differently depending on how many numbers we give.
 This is called Method Overloading → a type of Polymorphism
(many forms).
add2(5, 10) → will add 2 numbers
add3(5, 10, 15) → will add 3 numbers

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


 Different behavior
 Happens in inheritance
.
class Animal:
def sound(self):
return "Animals make sound"

class Dog(Animal): # Dog inherits Animal


def sound(self): # overriding
return "Dog barks"

class Cat(Animal): # Cat inherits Animal


28
def sound(self): # overriding
return "Cat meows"

# --- Usage ---


animal = Animal()
dog = Dog()
cat = Cat()

print([Link]()) # Parent method


print([Link]()) # Overridden by Dog
print([Link]()) # Overridden by Cat

 The method name is the same → sound()


 The behavior changes depending on which class is used.
 This is called Method Overriding → a type of Runtime
Polymorphism.

 Parent class (Animal) → sound() = “Animal makes a sound”


 Child class (Dog) → sound() = “Dog barks”

 Child class (Cat) → sound() = “Cat meows”

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.

2. What is Pseudo code?


Pseudocode is an informal high-level description of the operating principle of a computer
program or algorithm. Pseudo means false and code refers to instructions written in
programming language.

3. What is 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.

4. Distinguish between algorithm and program.

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.

5. Define Flow chart.


A graphical representation of an algorithm. Flow charts is a diagram made up of
boxes, diamonds, and other shapes, connected by arrows.

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.

[Link] Iteration Recursion


1. Iteration is a process of executing Iteration is a process of executing
certain set of instructions repeatedly, certain set of instructions
without calling the self function. repeatedly, by calling the
self function
repeatedly.
2. Iterative methods are more efficient Recursive methods are less
because of better execution speed. efficient.
3. It is simple to implement. Recursive methods are complex
to implement.

8. What is Programming language? With example.


Programming Language is a formal language with set of instruction, to the
computer to solve a problem. Java, C, C++, Python, PHP.

9. What are the steps for developing algorithms.


• Problem definition
• Development of a model
• Specification of Algorithm
• Designing an Algorithm
• Checking the correctness of Algorithm
• Analysis of Algorithm
• Implementation of Algorithm
• Program testing
• Documentation Preparation

10. What are the Guidelines for writing pseudo code?


 Write one statement perline
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent.

11. Draw a flow chart to find whether the given number is leap year or not

31
Start

Read year

If
(year%4==0)

Print ‘Leap year’ Print ‘Not Leap year’

Stop

32

You might also like