Wednesday 18 April 2018

Abstract Data types : Stack & Queue

A stack is abasic data structure whose physical representation can be compared to stack or pile of books or files which can be accessed only from the top. If we want to add a a file that will be to the top of stack and if we want to remove a file that will also be from the top.The insertion operation is called ' push' and to remove a file we say 'pop'. This basic implementation is called LIFO(Last In First Out) to demonstrate the way it accesses data.







There  are five basic types of operations that can be performed on stacks

1. stack()   creates an empty stack
2. push()    item. inserting an item to the top of stack (push)
3. pop()      removes the item from top of stack
4. peek()    returns the top item from the stack without removing it.
5. size()    returns the number of items in stack.

.
Here's the code depicting implementation  of stack:

class Stack():
def __init__(self):
self.item = []
def size(self):
return len(self.item)
def top(self):
if len(self.item) >= 1:
print self.item[len(self.item) -1]
else :
print "Empty list"
def pop(self):
if len(self.item) >= 1:
self.item.pop()
else:
raise IndexError
def push(self,item):
self.item.append(item)
print self.item



.............

Queue

A queue is a data structure similar to stack whose physical representation is similar to that of queue or a group of people standing in a line to collect tickets from movie theatre. Any person would join the queue at last (enqueue) and the person in front would collect the ticket and move out (dequeue) .  This basic implementation is called FIFO(First In FIrst Out)to demonstrate the way it accesses data.

There  operations that are performed using queue can be:

1. queue()   creates an empty stack
2. add()     inserting an item to the last of queue 
3. top()    returns the top item from queue without removing it.
4. size()    returns the number of items in queue. 

Example Code:


class Queue:
def __init__(self):
"""initialise a Queue class"""
self.items = []
def top(self):
"""returns the current element at front of queue"""
if self.items:
return self.items[0]
else:
raise Exception("Empty Queue")
def pop(self):
"""takes out an element from front of queue"""
if self.items:
self.items.pop(0)
else :
raise Exception("Empty Queue")
def add(self , item):
"""adds a new element at the end of queue"""
self.items.append(item)


No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...