我在尝试从队列中提取元素直到达到给定数量时遇到问题。如果给定的号码没有排队,代码应该将队列留空并给出一条消息。
相反,我收到此错误消息,但无法解决它:
Traceback (most recent call last):
File "python", line 45, in <module>
IndexError: list index out of range
这是我当前的代码:
class Queue():
def __init__(self):
self.items = []
def empty(self):
if self.items == []:
return True
else:
return False
def insert(self, value):
self.items.append(value)
def extract(self):
try:
return self.items.pop(0)
except:
raise ValueError("Empty queue")
def last(self):
if self.empty():
return None
else:
return self.items[0]
import random
def randomlist(n2,a2,b2):
list = [0] * n2
for i in range(n2):
list[i] = random.randint(a2,b2)
return list
queue1=Queue()
for i in range (0,10):
queue1.insert(randomlist(10,1,70)[i])
if queue1.empty()==False :
print("These are the numbers of your queue:\n",queue1.items)
test1=True
while test1==True:
s=(input("Input a number:\n"))
if s.isdigit()==True :
test1=False
s2=int(s)
else:
print("Wrong, try again\n")
for i in range (0,10) :
if queue1.items[i]!=s2 :
queue1.extract()
elif queue1.items[i]==s2 :
queue1.extract()
print ("Remaining numbers:\n",queue1.items)
break
if queue1.empty()==True :
print ("Queue is empty now", cola1.items)
最佳答案
extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that.
while not queue.empty():
if queue.extract() == target:
print('Found! Remaining numbers:', queue.items)
break
else:
print('Not found! Remaining numbers:', queue.items)
关于python - 从python队列中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477200/