Screen Link:
My Code:
class SupermarketQueue:
def __init__(self):
self.queue=[]
def add_to_back(self,element):
self.queue.append(element)
def remove_from_front(self):
return self.queue.pop(0)
def __str__(self):
string=self.queue
string.reverse()
return str(string)
def __len__(self):
return len(self.queue)
queue=SupermarketQueue()
queue.add_to_back('Alice')
queue.add_to_back('Bob')
print(queue.__len__())
print(queue)
print(queue.remove_from_front())
What I expected to happen:
2
[‘Bob’, ‘Alice’]
Bob
The above output is correct, I don`t get why it says the below error message
What actually happened:
Method str returned the wrong value.
Replace this line with the output/error
@shi.aaron
string=self.queue
is the major problem. string
points to the object self.queue.
So when you do string.reverse()
, it reverses self.queue
.
This print(queue.remove_from_front())
prints Bob
instead of Alice
as a result.
I introduced copy
and everything works fine.
import copy
class SupermarketQueue:
def __init__(self):
self.queue=[]
def add_to_back(self,element):
self.queue.append(element)
def remove_from_front(self):
return self.queue.pop(0)
def __str__(self):
string=copy.deepcopy(self.queue)
string.reverse()
return str(string)
def __len__(self):
return len(self.queue)
queue=SupermarketQueue()
queue.add_to_back('Alice')
queue.add_to_back('Bob')
print(queue.__len__())
print(queue)
print(queue.remove_from_front())
Without copy
, both string
and queue
have the same address.
def __str__(self):
string= self.queue
string.reverse()
print(id(string), id(self.queue))
return str(string)
Ouput: 140505287815424 140505287815424
I see where the issue is. Many thanks!
1 Like