I created a simple FIFO class below:
class Queue:
# Constructor, which creates a new empty queue:
def __init__(self):
self.items = []
# TODO: You must implement this constructor!
# Adds a new item to the back of the queue, and returns nothing:
def queue(self, item):
return self.items.append(item)
# TODO: You must implement this method!
# Removes and returns the front-most item in the queue.
# Returns nothing if the queue is empty.
def dequeue(self):
if len(self.items)==0:
return None
else:
return self.items.pop(0)
# TODO: You must implement this method!
# Returns the front-most item in the queue, and DOES NOT change the queue.
def peek(self):
if len(self.items)==0:
return None
else:
return self.items[0]
# TODO: You must implement this method!
# Returns True if the queue is empty, and False otherwise:
def is_empty(self):
return self.items == []
# TODO: You must implement this method!
# Returns the number of items in the queue:
def size(self):
return len(self.items)
# TODO: You must implement this method!
# Removes all items from thq queue, and sets the size to 0:
def clear(self):
while len(self.items) > 0:
self.items.pop()
# TODO: You must implement this method!
# Returns a string representation of the queue:
def __str__(self):
return repr(self.items)
# TODO: You must implement this method!
However, when using the class in another file, the dequeue() method does not seem to work, I am trying to implement a grocery store lineup where the demands are as follows:
The program should never allow more than 3 people in the lineup at once. If the user tries to add another person to the lineup when there are already 3 people, the program should print an error message and continue.
If the user tries to serve the next person when there is no one in the lineup, the program should inform the user that the lineup is empty. When a person is served, the program should print the name of that person.
This is my other file when I try to implement and use the class:
from queue import Queue
q=Queue()
exit==False
ase=input("Add, Serve, or Exit: ")
while ase=="Serve" and q.is_empty()== True and exit==False:
print("The lineup is already empty.")
ase=input("Add, Serve, or Exit: ")
if ase=="Exit":
exit==True
while (q.size()<3 and ase== "Add") or (q.size()<3 and ase== "Serve"):
add=input("Enter the name of the person to add: ")
ase=input("Add, Serve, or Exit: ")
q.queue(add)
print(q.__str__())
while q.size()==3 and ase=="Add":
print("You cannot add more people, the lineup is full!")
ase=input("Add, Serve, or Exit: ")
while ase=="Serve" and q.is_empty()==False and exit==False:
print(q.dequeue(), "has been served")
I know that it actually adds the names to the list but I do not know why it does nothing when the input is "Serve"
Also at the begging when I want it to print ("line up empty") it just doesn't even get to that line. Thoughts?