我創建了下面一個簡單的FIFO類: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!
然而,在另一個文件中使用類時,出列()方法似乎不工作,我想實現一個雜貨店陣容的需求如下:
該計劃不應該允許超過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")
我知道,這實際上增加了名稱列表中,但我不知道爲什麼它什麼也不做,當輸入「服務」
也在乞討時,我想它打印(「排隊空」),它甚至不會到那條線。思考?
非常好。我已經自己解決了,但我認爲這是比我更好的答案。 – 2015-01-31 21:25:00