Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue Class, dequeue and enqueue ? python

So I have this question and it says create a class queue and make the method dequeue and enqueue

Here's what I have so far, could someone direct me on the right track?

class queue:
      def __init__(self,queue):
            self.queue = []
      def dequeue(self):
            if len(queue) > 0:
                  e = queue[0]
                  queue = list[1:len(queue)]
            else:
                  return "There are no elements to remove"
      def enqueue(self,element):
            queue.insert([-1], element)
like image 879
user2928929 Avatar asked Dec 25 '22 16:12

user2928929


1 Answers

There are a few problems here.

  • queue by itself refers to your class, not to the instance's attribute with the same name, which is self.queue. You have to use the self. all the time. And it would really help to give the class and its attribute different names, to avoid this confusion. (It would also help to use PEP 8 style and name the class Queue.)
  • When the queue is not empty, you do compute the return value e, but you never return it; you just fall off the end of the function, which means you automatically return None.
  • list[1:len(queue)] is trying to slice the type list, not your actual list (self.queue). What you wanted is self.queue[1:len(queue)].
  • You probably don't want to return a string—which could be a perfectly valid thing to stick in the queue—on errors. That's exactly what exceptions are for.
  • Your __init__ takes an argument that it never uses. You probably wanted to use this as a starting value for the queue's contents. And you probably also want to make it optional.
  • The list.insert function doesn't take a list like [-1] for its first argument, it takes an index like -1.
  • If this is Python 2.x, you do not want to create classic classes; if you have nothing else to inherit from, inherit from `object.
  • It looks like you may be mixing tabs and spaces for indentation. Don't do that.

Plus, there are a few things that could be simpler:

  • If you want to slice to the end of a list, just leave off the end, like self.queue[1:], instead of using len(self.queue).
  • But to both fetch and remove a value from the left side of a list even more simply, you can use pop(0).
  • To add a value to the right side of a list, you can use append.
  • To check if a list is non-empty, just do if the_list, not if len(the_list) > 0. Empty collections are always falsey, and non-empty collections truth.
  • But you really don't need to check anyway—if the list is empty, pop will raise an exception, which is exactly what you wanted to do.

So:

class Queue(object):
    def __init__(self, queue=None):
        if queue is None:
            self.queue = []
        else:
            self.queue = list(queue)
    def dequeue(self):
        return self.queue.pop(0)
    def enqueue(self, element):
        self.queue.append(element)

If you want to customize the exception, so it says, e.g., IndexError: dequeue from empty Queue instead of IndexError: pop from empty list, you can do that with a try statement:

    def dequeue(self):
        try:
            return self.queue.pop(0)
        except IndexError:
            raise IndexError('dequeue from empty Queue') 

If you want to test that your queue class works properly, you will need to write test functions, and then call them. For example:

def test_queue():
    q = Queue()
    for i in range(10):
        q.enqueue(i)
    for i in range(10):
        value = q.dequeue()
        if value != i:
            print('Value #{} should be {} but is {}'.format(i, i, value))
    try:
        value = q.dequeue()
    except IndexError:
        pass # we _want_ an error here
    else:
        print('#10 should raise an IndexError, but got {}'.format(value))

if __name__ == '__main__':
    test_queue()

Now you can just run the file as a script, and it will run your tests.

In real life, you'll want to think of more complete tests that cover all the weird edge cases you can think of. And you'll probably want to use the unittest library or a third-party solution like nose to organize and simplify your tests.

like image 175
abarnert Avatar answered Dec 28 '22 05:12

abarnert