First of all, I'm a total beginner which is the reason that probably my code contains a few simple and dumb mistakes...but how you see I'm working on it ;)

My task is to write a program that contains a queue which will be returned in reversed order. But my problem is that some restrictions are made and at this moment I'm totally confused :( Maybe someone can help me a little.

Two functions are given:

def enqueue(self,z,q):   # z is an element, q = queue
        return q.append(z)
    
    def dequeue(self,q):
        return q.pop(0)

Further I'm only allowed to use one variable to buffer one element of queue. Calling len(q) and using controlvariables and parameters within loops is permitted.

So here is my sourcecode:

class Queue:
    
    def __init__(self):
        self.z = ""
        self.q = [] 
        
    def enqueue(self,z,q):
        return q.append(z)
    
    def dequeue(self,q):
        return q.pop(0)

    def queueReverse(q):
        n = 1
        print len(q)
        for x in range(len(q)-2):
            for x in range((len(q)-1)-n):
                enqueue(dequeue(q),q)
            a = dequeue(q)
            for x in range(n):
                enqueue(dequeue(q),q)
            enqueue(a,q)
            n += 1
        enqueue(dequeue(q),q)
        return q

#--------------- main ----------------

test = Queue()
q = [1,2,3,4,5,6,7]
test.queueReverse()
print q

So, in advance, thanx a lot!
Greetz

One problem is with the statement def queueReverse(q): because, if you want queueReverse() to be a method of Class Queue then the first argument shouldn't be named q, it should be named self.

When you later write test.queueReverse() the value of test is assigned to self when you get to queueReverse(). So all those instances of q inside queueReverse() need to be written as self.q. Do you see why?

If I understand the problem correctly, there is no need to pass q as an argument to enqueue() and dequeue().

def enqueue(self,z):
        self.q.append(z)
        return self.q

To reverse the queue, you can use a for loop on a range in reverse order: range(len(self.q)-1,-1,-1)

Notice the first number in the range is the index of the last element, and the range increment is -1.

A __str__() overload will enable printing the queue, but is not necessary except for the following example.

Example:
>>> test = Queue()
>>> for i in range(1,8):
... test.enqueue(i)
...
>>> print test
[1, 2, 3, 4, 5, 6, 7]
>>> test.queueReverse()
>>> print test
[7, 6, 5, 4, 3, 2, 1]
>>>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.