roboman
roboman

Reputation: 13

circular array class in python

I have a project to create a circular array class, and the language I will be using is python. I am new to classes in python, but after reading through some webpages and chapters in books I think I have an understanding of how they work. However I need help, so I figured I would come to the wonderful teachers here at SO :)

Our class must be able to implement several operations; insert at front, insert at back, insert at index, remove from front, remove from back, remove from index.

I have started coding but am running into some problems, and I am not 100% sure if my syntax is even right.

Here is what I have so far:

class circular:

    def __init__(self):
        self.store = []
        self.capacity = len(self.store)
        self.size = 0
        self.startIndex = 0
        self.endIndex = 0

    def decrementIndex(self):
        index = index - 1
        if index < 0:
            self.store = self.store + self.capacity

    def incrementIndex(self):
        index = index + 1
        if index == self.capacity:
            index = index - self.capacity

    def addToBack(self, value):
        self.store[self.endIndex] = value
        self.endIndex = incrementIndex(self.endIndex)
        self.size += 1

    def addToFront(self, value):
        if self.size == 0:
            addToBack(self, value)
        else:
            self.startIndex = decrementIndex(self.startIndex)
            self.store[self.startIndex] = value
            self.size += 1

I stopped there to start testing some of the functions, primarily t he addTofront and addToback. Upon testing them in IDLE using c = circular() and c.addToBack(2) I get an index error...and I'm not sure why. That isn't the only problem, it's just where I have gotten stuck and need help moving forward.

I am posting here because I need help and want to learn, not because I am lazy and haven't tried researching my problem. Thanks already SO!

Upvotes: 0

Views: 2280

Answers (1)

agf
agf

Reputation: 176760

In __init__ you set

self.store = []

In addToBack you do

self.store[self.endIndex] = value

If this is the first operation on the circular array, and you pass 2 as the value, then that turns into

[][0] = 2

The problem should be obvious -- an empty list has no index of 0, it has no indexes at all.

You need to add the item to the list in a different way.

I'm not going to tell you exactly how as it's part of your homework to figure that out.

Upvotes: 1

Related Questions