Introduction
Introduction
Data Structure:
Data Structure is a way to store and organize data so that it can be used efficiently.
The data structure name itself indicates that organizing the data in memory.
It is a set of algorithms that we can use in any programming language to structure
the data in the memory.
Data Structure can be defined as the group of data elements which provides an efficient
way of storing and organizing data in the computer so that it can be used efficiently. Some
examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Compiler Design
Statistical analysis package
Numerical analysis
Artificial intelligence
Operating system
DBMS
Simulation
Graphics
Operations on different Data Structure:
There are different types of operations that can be performed for the manipulation of data in
every data structure.
1) Traversing: Every data structure contains the set of data elements. Traversing the data
structure means visiting each element of the data structure in order to perform some specific
operation like searching or sorting.
2) Insertion: Insertion can be defined as the process of adding the elements to the data
3) Deletion: The process of removing an element from the data structure is called Deletion.
We can delete an element from the data structure at any random location.
4) Searching: The process of finding the location of an element within the data structure is
called Searching. There are two algorithms to perform searching, Linear Search and Binary
Search. We will discuss each one ofthem later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting.
There are many algorithms that can be used to perform sorting, for example, insertion sort,
selection sort, bubble sort, etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type
of elements, clubbed or joined to produce the third list, List C of size (M+N), then this
process is called merging
Data structures are generally categorized into two classes: primitive and non-primitive
Primitive data structures are the fundamental data types which are supported by a
programming language. Some basic data types supported by python are integer,
string, float, and Boolean.
Non-primitive data structures are those data structures which are created using
primitive data structures. Examples of such data structures include list, arrays,
tuple, set, file, and dictionary.
Four primitive variable types are defined in Python, and these are as follows:
STRINGS
BOOLEAN
FLOAT
INTIGERS
This data type is used to represent numerical data, that is, positive or negative whole
numbers without a decimal point. Say -1, 3, or 6.
String – This data type denotes a collection of alphabets, words or alphanumeric characters.
It is created by including a series of characters within a pair of double or single quotes.
Example: ‘blue’, ‘red’, etc.,
Boolean – This data type is useful in comparison and conditional expressions and can take
up the values
TRUE or FALSE
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).
Example:
t1 = ("apple", "banana", "cherry") print (t1)
Output:
(‘apple', 'banana', 'cherry')
Dictionary
Dictionaries are comprised of key-value pairs. The key is used to identify the item,
whereas the value is holding the item's value.
Thus, the telephone directory has a key (contact name) and the value (contact number)
assigned to that key.
A dictionary is a collection which is ordered, changeable and do not
allow duplicates. Dictionaries are written with curly brackets, and have
Creating a Dictionary
Dict = {1: 'apple', 2: 'ball'} print(Dict)
Output
{1: 'apple', 2: 'ball'}
Sets
A set is a collection which is unordered, unchangeable (i.e. it is not possible to edit set
elements) and disallows duplicate members.
However, unlike tuples, it is possible to add elements to or remove elements from a set
Creating a Set
A set is created by placing all the items (elements) inside curly braces { }, separated by
comma, or by using the built-in set( ) function.
It can have any number of items and they may be of different types (integer, float, tuple,
string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
Example:
s = {1,2,3} Or
s = {"apple", "banana", "orange"} Or
s = {"apple", "banana", 3, 4}
Linear Data Structures - If the elements of a data structure are stored in a linear or
sequential order, then it is a linear data structure.
Arrays:
An array is a collection of similar type of data items and each data item is called an element of
the array. The data type of the element may be any valid data type like char, int, float or
double.
Linked List:
Linked list is a linear data structure which is used to maintain a list in the memory. It can be
seen as the collection of nodes stored at non-contiguous memory locations. Each node of the
list contains a pointer to its adjacent node.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called
top.
It works based on the principle og LIFO (or) FILO
Queue:
Queue is a linear list in which elements can be inserted only at one end called rear and
deleted only at the other end called front.
Queue is opened at both end therefore it follows First-In-First-Out (FIFO) methodology
for storing the data items.
Non-Linear Data Structures.- If the elements of a data structure are not stored in a
sequential order, then it is a non-linear data structure. The relationship of adjacency is
not maintained between elements of a non-linear data structure. Examples include trees
and graphs.
Trees:
Trees are multilevel data structures with a hierarchical relationship among its elements
known as nodes. The bottommost nodes in the hierarchy are called leaf node while the
topmost node is called root node. Each node contains pointers to point adjacent nodes.
Graphs:
Graphs can be defined as the pictorial representation of the set of elements (represented by
vertices) connected by the links known as edges. A graph is different from tree in the sense
that a graph can have cycle while the tree can not have the one.
• Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Instance variable:
• Instance variables are for data, unique to each instance.
• class variables are for attributes and methods shared by all instances of the class.
• Instance variables are variables whose value is assigned inside a constructor or
method with self.
• class variables are variables whose value is assigned in the class.
Example:
class Employee
All classes have a function called init (), which is always executed when the class is being
initiated.
• init () function is used to assign values to object properties, or other operations
that are necessary to do when the object is being created.
• It runs as soon as an object of a class is instantiated.
• It is useful to do any initialization you want to do with your object.
The self:
• Class methods must have an extra first parameter in the method definition. We do
not give a value for this parameter when we call the method, Python provides it.
• If we have a method that takes no arguments, then we still have to have one
argument.
Output:
employee details are
Name: John
Ssn: 1234
Name: 30
Age: 8796
Example2:
class Employee:
ssn1=1234
def init (self, Name, Age):
self.Name = Name self.Age=Age
def display(self):
print(“employee details are”)
print(‘ssn:{} Name:{} Age:{} ‘.format(self.ssn1,self.Name,self.Age))
E1 = Employee("John", 36) E1.display()
Output:
employee details are
ssn: 1234
Name: John
Age: 36
Abstraction:
It is a technique of hiding the internal details from the user and only showing the
necessary details to the user.
Encapsulation:
It is a technique of combining the data and the member function in a single unit is
known as encapsulation.
Abstract Data type (ADT)
• Abstract Data type (ADT) is a type (or class) for objects whose behaviour is
defined by a set of value and a set of operations.
• The definition of ADT only mentions what operations are to be performed but
not how these operations will be implemented.
• It does not specify how data will be organized in memory and what algorithms
will be used for implementing the operations.
• It is called “abstract” because it gives an implementation-independent view.
The process of providing only the essentials and hiding the details is known as
abstraction.
• An ADT is a mathematical model of a data structure that specifies the type of
data stored, the operations supported on them, and the types of parameters of
the operations.
• It specifies what each operation does, but not how it does it. By hiding the
implementation details, we can work with an abstraction and focus on what
functionality the Abstract Data Type (ADT) provides instead of how that
functionality is implemented.
• The man only knows that pressing the accelerators will increase the speed of
car and applying breaks will stop the car.
• But he does not know about how on pressing accelerator ,the speed is actually
increasing and he does not know about the inner mechanism of the car or the
implementation of accelerator, breaks etc in the car
ADVANTAGES
o Helps the user to avoid writing the low level code.
o Avoid code duplication and increases reusability.
o Can change internal implementation of class independently without
affecting the user
o Helps to increase security of an application or program as only important
details are provided to the user.
EXP1. Python program to use and demonstrate basic data structures. Introduction:
Data Structures are a way of organizing data so that it can be accessed more efficiently
depending upon the situation.
Data Structures are fundamentals of any programming language around which a
program is built.
Basic data structure:
• Python include list, set, tuples, and dictionary.
• Each of the data structures is unique in its own way.
• Data structures are “containers” that organize and group data according to type.
List:
• List are just like dynamic sized arrays.
• Lists need not be homogeneous always which makes it the most powerful tool
in Python.
Example:
List_A = [item 1, item 2, item 3….., item n]
Tuple:
Example: set_a = {“item 1”, “item 2”, “item 3”,….., “item n”}
Dictionary:
• It is an ordered collection of data values.
• key: value pair. Key-value is provided in the dictionary to make it more
optimized.
Example: dict_a={key1:value1,key2:value2}
Implementation:
Step 1. Create and run your first Python project
print("List is:")
l1=[1,2,"ABC",3,"xyz",2,3]
print(l1) print("Dictionary")
d1={"a":134,"b":266,"c":434}
print(d1)
print("Tuples")
Output:
List is:
[1, 2, 'ABC', 3, 'xyz', 2, 3]
Dictionary
{'a': 134, 'b': 266, 'c': 434}
Tuples
(10, 20, 30, 50)
sets
{10, 20, 70, 60}
Exp2. Implement an ADT with all its operations. Abstract data type:
The abstract data type is special kind of data type, whose behavior is defined
by a set of values and set of operations.
The keyword “Abstract” is used as we can use these data types, we can
perform different operations. But how those operations are working that is
totally hidden from the user. The ADT is made of primitive data types, but
operation logics are hidden.
Types of ADT:
• Stack ADT
• Queue ADT
Stack Abstract Data Type:
Definition:
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO).
• In stack, a new element is added at one end and an element is removed from
same end only.
• The insert and delete operations are often called push and pop.
s=Stack()
print(s.isEmpty())
print("Push operation")
s.push(11)
s.push(12)
s.push(13)
print("Peek element of stack is :",s.peek())
print("Pop operation")
print(s.pop())
OUTPUT:
True
Push operation
11
12
13
Peek element of stack is : 13 Pop operation
13
class Queue:
def init (self):
self.items = []
def isEmpty(self):
return self.items == []
Output:
True
Enqueue: inserting elements into queue 11
12
13
Front 13
Dequeue: deleting elements from queue 11
12