|
| 1 | +# Implementation of a queue using an array |
| 2 | +# Python 3 |
| 3 | +# Aitor Alonso (https://github.com/tairosonloa) |
| 4 | + |
| 5 | +class QueueArray: |
| 6 | + def __init__(self): |
| 7 | + self.items = [] |
| 8 | + |
| 9 | + def isEmpty(self): |
| 10 | + return self.items == [] |
| 11 | + |
| 12 | + def enqueue(self, item): |
| 13 | + # We always enqueue into last position |
| 14 | + self.items.append(item) |
| 15 | + |
| 16 | + def dequeue(self): |
| 17 | + # We always dequeue from first position |
| 18 | + return self.items.pop(0) |
| 19 | + |
| 20 | + def size(self): |
| 21 | + return len(self.items) |
| 22 | + |
| 23 | + def printQueue(self): |
| 24 | + print ("FIRST>", end=" ") |
| 25 | + for item in self.items: |
| 26 | + print(item, end=" ") |
| 27 | + print ("<LAST") |
| 28 | + |
| 29 | +if __name__ == "__main__": |
| 30 | + # execute only if run as a script, small demostration of working, just run 'python3 QueueArray.py' in a terminal |
| 31 | + queue = QueueArray() |
| 32 | + while True: |
| 33 | + print("What do you want to do?") |
| 34 | + print("\t1 - Enqueue") |
| 35 | + print("\t2 - Dequeue") |
| 36 | + print("\t3 - Check empty") |
| 37 | + print("\t4 - Check size") |
| 38 | + print("\t5 - Print queue") |
| 39 | + print("\t6 - Exit") |
| 40 | + option = input() |
| 41 | + print() |
| 42 | + if option == '1': |
| 43 | + item = input("Type your item ") |
| 44 | + queue.enqueue(item) |
| 45 | + print("Item enqueued successfully!\n") |
| 46 | + elif option == '2': |
| 47 | + item = queue.dequeue() |
| 48 | + print("Dequeue item" , item, "\n") |
| 49 | + elif option == '3': |
| 50 | + if queue.isEmpty(): |
| 51 | + print("Queue is empty\n") |
| 52 | + else: |
| 53 | + print("Queue is not empty\n") |
| 54 | + elif option == '4': |
| 55 | + print("The queue size is", queue.size(), "\n") |
| 56 | + elif option == '5': |
| 57 | + queue.printQueue() |
| 58 | + print() |
| 59 | + elif option == '6': |
| 60 | + print("Bye!") |
| 61 | + break |
| 62 | + else: |
| 63 | + print("Please, choose an option between 1 and 6\n") |
| 64 | + |
0 commit comments