Professional Documents
Culture Documents
UNIT Contents
UNIT – I
INTRODUCTION
DATA + STRUCTURE
DATA: The data means a collection of facts, concepts or instructions in a formalized
manner suitable for communication or processing. Processed data is called as
Information.
STRUCTURE: The formation or arrangements of data in some order in the
computer’s memory.
Data structure is a storage that is used to store and organize data. It is a way of
arranging data on a computer so that it can be accessed and updated efficiently.
A class is a new kind of data type. Each class includes data and also has the
ability to include constructors and methods. Once you have created the class
(constructor, instance variables and methods) you may create objects of this class. Use
the keyword "new" to give it a name.
An ADT defines operations for the given type and mathematically expresses
their behaviour. Concrete implementations of an ADT can differ from each other. In
that way classes are implementing the ADT and methods implement operations.
Classes have a slightly different terminology than ADTs and add other characteristics,
like:
Introduction to OOP
Object-oriented programming (OOP) is a method of structuring a program by
bundling related properties and behaviors into individual objects.
Encapsulation
Inheritance
Data Abstraction
Objects
The object is an entity that has a state and behavior associated with it. It may
be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers,
strings, floating-point numbers, even arrays, and dictionaries, are all objects.
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.
Inheritance
Inheritance is the capability of one class to derive or inherit the properties
from another class. The class that derives properties is called the derived class or
child class and the class from which the properties are being derived is called the
base class or parent class.
Polymorphism
Polymorphism simply means having many forms. For example, we need to
determine if the given species of birds fly or not, using polymorphism we can do this
using a single function.
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of wrapping data and the methods that
work on data within one unit. This puts restrictions on accessing variables and
methods directly and can prevent the accidental modification of data.
Data Abstraction
It hides unnecessary code details from the user. Also, when we do not want to
give out sensitive parts of our code implementation and this is where data abstraction
came.
Classes in Python
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.
To understand the need for creating a class let’s consider an example, let’s say
you wanted to track the number of dogs that may have different attributes like breed,
and age.
def speak(self):
print("My name is {}".format(self.name))
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
Output
My name is Rodger
My name is Tommy
Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class. Parent class is the class being inherited from, also called
base class. Child class is the class that inherits from another class, also called derived
class.
output:
dog barking
Animal Speaking
Namespaces
A namespace is an abstraction that manages all of the identifiers that are
defined in a particular scope, mapping each name to its associated value. In Python,
functions, classes, and modules are all first-class objects, and so the “value” associated
with an identifier in a namespace may in fact be a function, class, or module
A namespace is a system that has a unique name for each and every object in
Python. An object might be a variable or a method. Python itself maintains a
namespace in the form of a Python dictionary.
Types of namespaces :
1. Built-In
2. Global
3. Local
The built-in namespace contains the names of all of Python’s built-in objects. These
are available at all times when Python is running.
print(name)
The global namespace contains any names defined at the level of the main
program. Python creates the global namespace when the main program body starts,
and it remains in existence until the interpreter terminates.
That namespace is local to the function and remains in existence until the
function terminates.
EX:
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
return temp
Shallow Copy
A shallow copy creates a new object which stores the reference of the original elements.
Ex:
import copy
p Copy
eep copy creates a new object and recursively adds the copies of nested objects present in the original
import copy
output
Asymptotic Notations
Asymptotic notations are used to represent the complexities of algorithms for
asymptotic analysis. These notations are mathematical tools to represent the
complexities. There are three notations that are commonly used.
Big Oh Notation
Big-Oh (O) notation gives an upper bound for a function f(n) to within a
constant factor.
We write f(n) = O(g(n)), If there are positive constantsn0 and c such that, to the
right of n0 the f(n) always lies on or below c*g(n).
O(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ f(n) ≤ c
g(n), for all n ≥ n0}
Big Omega Notation
Big-Omega (Ω) notation gives a lower bound for a function f(n) to within a
constant factor.
We write f(n) = Ω(g(n)), If there are positive constantsn0 and c such that, to the
right of n0 the f(n) always lies on or above c*g(n).
Ω(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ c g(n) ≤
f(n), for all n ≥ n0}
Big Theta Notation
Big-Theta(Θ) notation gives bound for a function f(n) to within a constant
factor.
Recursion
Recursion can be defined as the process of defining something in terms of
itself. In simple words, it is a process in which a function calls itself directly or
indirectly.
Properties:
The algorithms must have a base case.
The algorithms should call themselves recursively.
The algorithm must change its state and move toward the base case.
Advantages
A complicated function can be split down into smaller sub-problems utilizing
recursion.
Sequence creation is simpler through recursion than utilizing any nested
iteration.
Recursive functions render the code look simple and effective.
DisAdvantages
A lot of memory and time is taken through recursive calls which makes it
expensive for use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
Ex:
def function():
x = 10
function()
FACTORIAL CALCULATION
The calculation of factorial value for an integer n is:
n! = n * (n-1) * (n-2) * …….* 3 * 2 * 1 [Or] n! = n * (n-1)
FACTORIAL (N)
Steps:
1. if (N =0) then fact = 1
2. else fact = N * FACTORIAL(N-1)
3. end if
4. return
5. stop
Steps:
1. val = N, top = 0, addr = step 10
2. PUSH (val, addr) //initialize the stack
3. val = val – 1, addr = step 7 //next value and return address
4. if (val= 0) then
1. fact = 1
2. Go to step 8
5. else
Algorithm:
To solve the problem, the following steps can be followed :
1) Move the top N – 1 discs from Source to Temp (using Target as
intermediary pillar).
TOH ( N – 1 , Source , Target , Temp )
2) Move the bottom disc from Source to Target.
Move from Source to Target
3) Move N – 1 discs from Temp to Target (using Source as an
intermediary pillar).
(b) Move the top N – 1 discs from Source to Temp (using Target as intermediary
pillar)
(i)
(ii)
Source Temp Target
(i)
(iii)
Source Temp Target
UNIT II
Linear Structures:
List ADT:
Lists are linear data structures in which data is stored in a non - continuous fashion.
List consists of data storage boxes called 'nodes'. These nodes are linked to each other
node consists of the address of some other block.
Ex: lists of integers, lists of characters, lists of payroll records, even lists of lists.
Arraybased implementations
An array is a linear data structure that collects elements of the same data type
and stores them in contiguous and adjacent memory locations.
Arrays work on an index system starting from 0 to (n-1), where n is the size of
the array.
Basic operations
o Traversal - This operation is used to print the elements of the array.
o Insertion - It is used to add an element at a particular index.
o Deletion - It is used to delete an element from a particular index.
o Search - It is used to search an element using the given index or by the value.
o Update - It updates an element at a particular index.
Insertion Operation
In the insertion operation, we are adding one or more elements to the array. Based on the requirement, a new
element can be added at the beginning, end, or any given index of array. This is done using input statements of
the programming languages.
Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach the end of the array −
1. Start
2. Create an Array of a desired datatype and size.
3. Initialize a variable ‘i’ as 0.
4. Enter the element at ith index of the array.
5. Increment i by 1.
6. Repeat Steps 4 & 5 until the end of the array.
7. Stop
Deletion Operation
In this array operation, we delete an element from the particular index of an array. This deletion operation takes
place as we assign the value in the consequent index to the current index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to delete an element available at the K th position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after deletion :
LA[0] = 1
LA[1] = 5
Search Operation
Searching an element in the array using a key; The key element sequentially compares every value in the array
to check if the key is present in the array or not.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to find an element with a value of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Traversal Operation
This operation traverses through all the elements of an array. We use loop statements to carry this out.
Algorithm
Following is the algorithm to traverse through all the elements present in a Linear Array −
1 Start
2. Initialize an Array of certain size and datatype.
3. Initialize another variable ‘i’ with 0.
4. Print the ith value in the array and increment i.
5. Repeat Step 4 until the end of the array is reached.
6. End
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Update Operation
Update operation refers to updating an existing element from the array at a given index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to update an element available at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
Linked Lists:
Linked lists are one of the most commonly used data structures in any
programming language.Linked Lists, on the other hand, are different. Linked
lists, do not store data at contiguous memory locations. For each item in the
memory location, linked list stores value of the item and the reference or
pointer to the next item. One pair of the linked list item and the reference to
next item constitutes a node.
Insertion
There are three possible positions where we can enter a new node in a single linked list –
Insertion at beginning
Insertion at beginning
Imagine our linked list is not necessarily sorted and there is no reason to insert a new node in any special place
in the list. Then we have an easiest place to insert the node is at the beginning of the list. An algorithm that does
so follows.
WriteOVERFLOW
GotoStep7
[END OF IF]
Step 7: EXIT
Insertion at ending
To insert element in linked list last we would use the following steps to insert a new Node at the last of
the single linked list.
Now give the address of the new node in previous node means link the new node with previous node.
After this, give the address of current node in new node.Means link your new node also with current node.
Algorithm
Traverse the Linked List till the nth node
Allocate the data and memory for the new node
Assign the next pointer of the specific nth position node to this new node
Assign the next pointer of this newNode to (n+1)th node (Nth node’s next)
Deletion
Deletion at beginning
Deletion at middle
Deletion at last
Deletion at beginning
So in this diagram Node, A had been deleted, and after delete, the node will be shown in the diagram.
Algorithm
Deletion at middle
Algorithm
Deletion at last
Each node contains three fields: two link fields (references to the previous
and to the next node in the sequence of nodes) and one data field.
1. Traversal can be done on either side means both in forward as well as backward.
1. Since it requires extra pointer that is the previous pointer to store previous node reference.
3 fields:
There are three possible positions where we can enter a new node in a single linked list –
Insertion at beginning
Insertion after nth position
Insertion at end
Insertion at beginning
Insertion at end
Deletion
Deletion at beginning
Deletion at middle
Deletion at last
Deletion at beginning
STEP 1:
IF HEAD = NULL
WRITE UNDERFLOW
GOTO STEP 6
STEP 2: SET PTR = HEAD
STEP 3: SET HEAD = HEAD → NEXT
STEP 4: SET HEAD → PREV = NULL
STEP 5: FREE PTR
STEP 6: EXIT
1. Insertion
2. Deletion
1. Insertion in the circular linked list:
A node can be added in three ways:
And then,
2) Insertion at the end of the list: To insert a node at the end of the list, follow these steps:
Create a node, say T.
Make T -> next = last -> next;
last -> next = T.
last = T.
Before insertion,
After insertion,
3) Insertion in between the nodes: To insert a node in between the two nodes, follow these steps:
Create a node, say T.
Search for the node after which T needs to be inserted, say that node is P.
Make T -> next = P -> next;
P -> next = T.
Suppose 12 needs to be inserted after the node has the value 10,
1) Delete the node only if it is the only node in the circular linked list:
Free the node’s memory
The last value should be NULL A node always points to another node, so NULL assignment is not necessary.
Any node can be set as the starting point.
Nodes are traversed quickly from the first to the last.
2) Deletion of the last node:
Locate the node before the last node (let it be temp)
Keep the address of the node next to the last node in temp
Delete the last memory
Put temp at the end
3) Delete any node from the circular linked list: We will be given a node and our task is to delete that node from the circular
linked list.
Algorithm:
Case 1: List is empty.
If the list is empty we will simply return.
Case 2:List is not empty
If the list is not empty then we define two pointers curr and prev and initialize the pointer curr with the head node.
Traverse the list using curr to find the node to be deleted and before moving to curr to the next node, every time set prev
= curr.
If the node is found, check if it is the only node in the list. If yes, set head = NULL and free(curr).
If the list has more than one node, check if it is the first node of the list. Condition to check this( curr == head). If yes,
then move prev until it reaches the last node. After prev reaches the last node, set head = head -> next and prev -> next =
head. Delete curr.
If curr is not the first node, we check if it is the last node in the list. Condition to check this is (curr -> next == head).
If curr is the last node. Set prev -> next = head and delete the node curr by free(curr).
If the node to be deleted is neither the first node nor the last node, then set prev -> next = curr -> next and delete curr.
If the node is not present in the list return head and don’t do anything.
Advantages of circular linked list:- It saves time when we have to go to the first node
from the last node. But in double linked list we have to go through in between nodes.
Linked list applications:-
1.Polynomials can be represented and various operations can be performed on
polynomials using linked lists.
2.Sparse matrix can be represented using linked list.
3.Various details like student details, customer details , product details and so on can
be implemented using linked list.
Ex:- 8x6+5x4+2x+9
Where 8,5,2 and 9 are coefficients while 6,4,1 and 0 are exponents.
We can perform various operations on polynomial such as addition,
subtraction, multiplication and division.