我在下面创建了一个简单的 FIFO 类:
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!
但是,当在另一个文件中使用该类时,dequeue() 方法似乎不起作用,我正在尝试实现一个杂货店阵容,其中的需求如下:
该程序不应允许超过 3 人在阵容中 一次。如果用户在以下时间尝试将另一个人添加到阵容中 已经有 3 个人,程序应该打印错误 消息并继续。
如果用户在没有人的情况下尝试为下一个人服务 阵容,程序应该通知用户阵容是空的。 当一个人被送达时,程序应该打印那个人的名字 人。
这是我尝试实现和使用该类时的另一个文件:
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")
我知道它实际上将名称添加到列表中,但我不知道为什么当输入为“Serve”时它什么都不做
同样在开始时,当我想要它打印时(“排空”)它甚至没有到达那条线。想法?
请您参考如下方法:
在我看来,您的 exit 变量有问题:它在第一个循环结束时设置为 True。但是您的 Serve 循环期望输入为 False...
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 ase=="Serve" and q.is_empty()==False and exit==False:
# ^^^^^^^^^^^
print(q.dequeue(), "has been served")
