Reputation: 1
This is a homework question and I don't know if my code is right or wrong. Question: How can I print the stack (hence know if the code is working or not)? If wrong, what should I change.
What I have:
class stack:
def __init__(self):
self.q1 = []
self.q2 = []
def isEmpty(self):
return self.size()==0
def pop(self):
return self.q1.pop(0)
def push(self, item):
self.q2.append(item)
for i in range (len(self.q1)):
self.q2.append(self.q1.pop)
self.q2 = self.q1
print (self.q1)
s = stack()
s.push('2')
print (s)
Upvotes: 0
Views: 416
Reputation: 365717
How can I print the stack?
Well, there's one obvious possibility, which doesn't depend on your implementation at all (which makes it a great unit test): Just look around s.pop()
until it fails:
while True:
try:
print(s.pop())
except IndexError:
break
But what if you want to test non-destructively? Well, there are two options there.
First, staying with the "black box" approach, if you assume that push
works properly, you can take advantage of the invariants of what a stack is supposed to do to print out the stack while building a copy:
s2 = stack()
while True:
try:
value = s.pop()
except IndexError:
break
else:
print(value)
s2.push(value)
Of course that gives you a reversed stack, so you'll want to loop over that again, reversing s2
back into s
:
while True:
try:
value = s2.pop()
s.push(value)
except IndexError:
break
Second, you can switch to a white-box approach. What does pop
do? Well, it returns the last value in q1
, and removes it. So, if you call pop
repeatedly, it's just going to return the values in q1
in reverse order. So:
for value in reversed(s.q1):
print(value)
But if you run any of these, you're going to see that the stack is always empty. Why? Well, let's look at your push
:
def push(self, item):
self.q2.append(item)
for i in range (len(self.q1)):
self.q2.append(self.q1.pop)
OK, the first problem is here: you forgot to call pop
here, so you're just appending the method self.q1.pop
itself, rather than popping a value and appending the result.
self.q2 = self.q1
And here, you've done all this work to move all the values from q1
to q2
, and then you replace q2
—which has all your values—with q1
—which is empty.
But, even if you fix that, what is q1
actually doing? It's always empty at the start. It's always empty after a push
. It's always shorter after a pop
. So it can't possibly ever have anything in it. So clearly, you have a fundamental problem with your design, and there's no way to fix the implementation of a broken design.
Upvotes: 1