0% found this document useful (0 votes)
19 views

Introduction

Uploaded by

HUSNA JABEEN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Introduction

Uploaded by

HUSNA JABEEN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

DATA STRUCTURE USING PYTHON CODE: 20CS41P

INTRODUCTION TO DATA STUCTURE

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.

Data structures are widely applied in the following areas:

 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

structure at any location.

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.

SEARCH EDUCATIONS Page 1


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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

Characteristics of a Data Structure

 Correctness − Data structure implementation should implement its interface correctly.

 Time Complexity − Running time or the execution time of operations of data


structure must be as small as possible.

 Space Complexity − Memory usage of a data structure operation should be as little as


possible.

Classification of Data Structure

SEARCH EDUCATIONS Page 2


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Data structures are generally categorized into two classes: primitive and non-primitive

data structures. Primitive and Non-primitive Data Structures

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

The Primitive Data Structures

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.

Float – Float signifies ‘floating-point real number’. It is used to represent rational


numbers, usually containing a decimal point like 2.0 or 5.77.

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

SEARCH EDUCATIONS Page 3


DATA STRUCTURE USING PYTHON CODE: 20CS41P

The Non-Primitive Data Structures


 Non-Primitive data Structures act as the complex components of the data structures
family. Instead of storing a value, these data structures have a collection of values in
different formats.
Examples
TUPLES
 Tuples are used to store multiple items in a single variable.
 A tuple is a collection of objects which ordered and immutable.
 A tuple is a collection which is ordered and unchangeable. In tuple, we cannot change
the elements of a tuple once it is assigned.
 Tuples are written with round brackets.

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

keys and values:

SEARCH EDUCATIONS Page 4


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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}

The non-primitive data structure is divided into two types:


 Linear data structure
 Non-linear data structure

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.

Example of Linear Data Structures are given below:

SEARCH EDUCATIONS Page 5


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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

SEARCH EDUCATIONS Page 6


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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.

Example of Non Linear Data Structures are given below:

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.

SEARCH EDUCATIONS Page 7


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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.

It is represented as G={V,E} Where V-> vertices

SEARCH EDUCATIONS Page 8


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Introduction to Class and Objects:


Definition:
`Class is an ADT which creates a user-defined data structure, it holds its own data members
and member functions, which can be accessed and used by creating an instance of that class.
A class is like a blueprint for an object.
Class and objects in python:
• A class is a user-defined blueprint from which objects are created.
• Classes provide a means of bundling data and functionality together.
• Creating a new class creates a new type of object, allowing new instances of that
type to be made. Each class instance can have attributes attached to it for maintaining
its state.

Creating a class in Python:


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

Class Definition Syntax:


class ClassName: # Statement-1
.
.
.
# Statement-N
Class Objects
• An Object is an instance of a Class.
• A class is like a blueprint while an instance is a copy of the class with actual
values.

• State: It is represented by the attributes of an object. It also reflects the properties


of an object.
• Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.

SEARCH EDUCATIONS Page 9


DATA STRUCTURE USING PYTHON CODE: 20CS41P

• 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

Name=’Ramesh’ #class variables Age=25

def emp_details(self) #class method

print (“my name is:”, self.Name) #instance variables


print (“my age is:”, self.Age)
E1=Employee () #object instantiation / object creation E1.emp_details () #accessing
class method
print (“employee name is:”, e1.name)

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:

SEARCH EDUCATIONS Page 10


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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

Example1 class Employee:


ssn1=1234
ssn2=8796
def init (self, Name, Age):
self.Name = Name self.Age=Age
E1 = Employee("John", 36) E2=Employee(“Smith”,30)
print(“employee details are”)
print(‘Name:{} Ssn:{} ‘.format(E1.Name,E1.ssn1))
print(‘Age : {} Ssn : {}’.format(E2.Age,E2,ssn2))

Output:
employee details are
Name: John
Ssn: 1234
Name: 30
Age: 8796

SEARCH EDUCATIONS Page 11


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Fig: Relationship between class and objects

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

SEARCH EDUCATIONS Page 12


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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.

REAL LIFE EXAMPLE OF ABSTRACTION


Man Driving a Car

• 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

SEARCH EDUCATIONS Page 13


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Abstract Data Type (ADT) model.


• There are two types of function in the ADT model, i.e., the public function and
the private function.
• The ADT model also contains the data structures that we are using in a
program.
• In this model, first encapsulation is performed, i.e., all the data is wrapped in a
single unit, i.e., ADT.
• Then, the abstraction is performed means showing the operations that can be
performed on the data structure and what are the data structures that we are
using in a program.
IMPLEMENTATION OF ADT
• A wall of ADT operations isolates a data structure from the program that uses
it
• Implementation details should be hidden behind a wall of ADT operation
• A program would only be able to access the data structure

PROGRAM LOGIC FORMULATION


• Outline your algorithm
• Identify which data operations are used
• Select ADT containing those operations
• Select the data structure for the ADT
• Write program

VARIOUS ABSTRACT DATA TYPE


Examples
 Defining String ADT
 Defining Date ADT
 Defining Stack ADT
Date( month, day, year ): Creates a new Date instance initialized to the given date .
day(): Returns the day number of the given date.
month(): Returns the month number of the given date. year(): Returns the year of the
given date.

SEARCH EDUCATIONS Page 14


DATA STRUCTURE USING PYTHON CODE: 20CS41P

monthName(): Returns the month name of the given date.


isLeapYear(): Determines if this date falls in a leap year and returns the appropriate
boolean value.
A stack is structured as an ordered collection of items where items are added to and
removed from the end called the “top”.Stacks are ordered LIFO.
Stack(): creates a new stack that is empty. It needs no parameters and returns an empty
stack. push(item): adds a new item to the top of the stack. It needs the item and returns
nothing. pop(): removes the top item from the stack.
peek(): returns the top item from the stack but does not remove it. It needs no
parameters. The stack is not modified.
isEmpty(): tests to see whether the stack is empty. It needs no parameters and returns a
boolean value.

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.

SEARCH EDUCATIONS Page 15


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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.

Fig: Basic data structure in python

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:

SEARCH EDUCATIONS Page 16


DATA STRUCTURE USING PYTHON CODE: 20CS41P

• Tuple is a collection of Python objects separated by commas.


• Tuple is immutable unlike lists which are mutable.

Example: tuple_A = (item 1, item 2, item 3,…, item n)


Sets:
• A Set is an unordered collection data type.
• Iterable, mutable, and has no duplicate elements.

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

SEARCH EDUCATIONS Page 17


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Step 2.Create python file under the respective project.

Step 3. Type following code in pycharm IDE.

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}

SEARCH EDUCATIONS Page 18


DATA STRUCTURE USING PYTHON CODE: 20CS41P

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.

Ex: Stacking of plates

The functions associated with stack are:


• Stack(): creates a new stack that is empty. It needs no parameters and returns
an empty stack.
• push(item): adds a new item to the top of the stack. It needs the item and
returns nothing.
• pop(): removes the top item from the stack. It needs no parameters and returns
the item. The stack is modified.
• peek(): returns the top item from the stack but does not remove it. It needs no
parameters. The stack is not modified.
• isEmpty(): tests to see whether the stack is empty. It needs no parameters and
returns a boolean value.

SEARCH EDUCATIONS Page 19


DATA STRUCTURE USING PYTHON CODE: 20CS41P

Implementation of stack ADT


class Stack:
def init (self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self, item):
self.items.append(item)
print(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]

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

Queue ADT: Definition:


• Queue is a linear data structure that stores items in First In First Out (FIFO) manner.
• With a queue the least recently added item is removed first.
Ex: customer standing in a queue.
The functions associated with queue are:
a. Enqueue: Adds an item to the queue.
b. Dequeue: Removes an item from the queue. The items are popped in the same
order in which they are pushed.
c. Front: Get the front item from queue.

SEARCH EDUCATIONS Page 20


DATA STRUCTURE USING PYTHON CODE: 20CS41P

d. Rear: Get the last item from queue.

Implementation of queue ADT:

class Queue:
def init (self):
self.items = []

def isEmpty(self):
return self.items == []

def enqueue(self, item):


self.items.append(item)
print(item)
def front(self):
return self.items[len(self.items)-1]
def dequeue(self):
return self.items.pop(0)
q=Queue()
print(q.isEmpty())
print("Enqueue:inserting elements into queue")
q.enqueue(11)
q.enqueue(12)
q.enqueue(13)
print("Front:elemenet at front end",q.front())
print("Dequeue:deleting elements from queue")
print(q.dequeue())
print(q.dequeue())

Output:
True
Enqueue: inserting elements into queue 11
12
13
Front 13
Dequeue: deleting elements from queue 11
12

SEARCH EDUCATIONS Page 21

You might also like