I run this script and I don't understand how the list reversal works.
class Queue:
def __init__(self):
self._push_stack = list()
self._pop_stack = list()
def push(self, x):
self._push_stack.append(x)
self._pop_stack.append(x)
self._pop_stack.reverse()
print(self._push_stack, self._pop_stack) # debugging
def pop(self):
if len(self._pop_stack) == 0:
raise IndexError("pop from an empty queue")
else:
self._push_stack.pop()
return self._pop_stack.pop()
queue = Queue()
queue.push(3)
queue.push(5)
queue.push(7)
queue.push(9)
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.pop())
The output for this script is:
[3] [3]
[3, 5] [5, 3]
[3, 5, 7] [7, 3, 5]
[3, 5, 7, 9] [9, 5, 3, 7]
7
3
5
9
What I don't understand is why [3, 5, 7]
, when reversed, is [7, 3, 5]
and not [7, 5, 3]
; why [3, 5, 7, 9]
, when reversed, is [9, 5, 3, 7]
, and not [9, 7, 5, 3]
.
PS please ignore other shortcomings of the script.