Can't push values in a queue and stuck on only first and last input(python)

Viewed 25

I've wanted to make simple queue with self parameter, however face with output problem in which my values I've added to the queue are only first and last on first and second positions, all in between is being ignored and placed zero's instead(as created).

class Queue():
    data = []
    r = 0
    f = 0
    maxSize = 0
    size = 0
    def __init__(self,maxSize):
        self.maxSize = maxSize
        self.data = [0.0]*maxSize

    def addValue(self, val):
        if self.size == self.maxSize:
            print('Queue overflow')
        else:
            self.data[self.r] = val
            self.r =+ 1
            self.size =+ 1

    def printQ(self):
        if self.size == 0:
            print('[]')
        else:
            print('[',end='')
            for i in range(0,len(self.data)):
                print(self.data[i],end=',')
            print(']')

myQueue = Queue(7)
print(myQueue.isEmpty())
myQueue.addValue(12)
myQueue.addValue(135)
myQueue.addValue(1)
myQueue.addValue(5)
myQueue.addValue(19)
myQueue.addValue(123)
myQueue.addValue(2222)

print(myQueue.isEmpty())
myQueue.printQ()

The output is:

True
False
[12,2222,0.0,0.0,0.0,0.0,0.0,]
2 Answers
self.r =+ 1
self.size =+ 1

should be

self.r += 1
self.size += 1

You should also probably be assigning:

data = []
r = 0
f = 0
maxSize = 0
size = 0

all as instance variables in the constructor instead of declaring them as class variables

I don't know what is the use of the r and [0.0]*maxSize but this code works:

class Queue():
    data = []
    f = 0
    maxSize = 0
    size = 0

    def __init__(self,maxSize):
        self.maxSize = maxSize
        self.data = []

    def addValue(self, val):
        if self.size == self.maxSize:
            print('Queue overflow')
        else:
            self.data.append(val)
            self.size =+ 1

    def printQ(self):
        if self.size == 0:
            print('[]')
        else:
            print('[',end='')
            print(",".join(str(x) for x in self.data),end='')
            print(']')

    def isEmpty(self):
      return len(self.data) == 0

myQueue = Queue(7)
print(myQueue.isEmpty())
myQueue.addValue(12)
myQueue.addValue(135)
myQueue.addValue(1)
myQueue.addValue(5)
myQueue.addValue(19)
myQueue.addValue(123)
myQueue.addValue(2222)

print(myQueue.isEmpty())
myQueue.printQ()

# prints
# True
# False
# [12,135,1,5,19,123,2222,]
Related