Sunday, September 16, 2012

Data Structures in Python

Currently I'm working on learning Python and have been working through various books.

A few of the exercises in the book Core Python Programming 2e ask the reader to implement data structures as classes, specifically stacks and queues.

For those who do not know what a data structure is, you can read about it here.  A stack is a Last-In-First-Out (LIFO) data structure and a queue is a First-In-First-Out (FIFO) data structure.

I chose to use Python's built in list functionality to implement the classes.  The solutions proved to be very simple as opposed to the same solutions being produced in a language like C.

Here is the code:

Stack

class stack(object):
    def __init__(self):
        self.stack = list()

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        self.stack.pop(len(self.stack)-1)

    def isempty(self):
        if len(self.stack) == 0:
            return True
        else:
            return False
   
    #displays the last element of the stack
    def peek(self):
        return self.stack[len(self.stack)-1]

Queue

class queue(object):
    def __init__(self):
        self.queue = list()

    def enqueue(self, item):
        self.queue.append(item)

    def dequeue(self):
        return self.queue.pop(0)

    def isempty(self):
        if len(self.queue) == 0:
            return True
        else:
            return False

    #displays the first element of the queue
    def peek(self):
        return self.queue[0]

Hybrid Stack/Queue

class stackQueue(object):
    def __init__(self):
        self.stackQueue = list()

    def shift(self):
        return self.stackQueue.pop(0)

    def unshift(self, item):
        self.stackQueue.insert(0,item)

    def push(self, item):
        self.stackQueue.append(item)

    def pop(self):
        return self.stackQueue.pop(len(self.stackQueue)-1)

    def isempty(self):
        if len(self.stackQueue) == 0:
            return True
        else:
            return False

     #returns the first element of the data structure
    def peek(self):
        return self.stackQueue[0]


No comments:

Post a Comment