I'm having a problem trying to 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.
Instead, I get this error message, but I'm not able to solve it:
Traceback (most recent call last):
File "python", line 45, in <module>
IndexError: list index out of range
This is my current code:
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)
def randomlist(n2,a2,b2)islist(random.choices(range(a2,b2+1),k=n2)list,dictor any other reserved word as variablename - your variable is shadowing the inbuild type and you run into problems.