python - Iplementing a stack using 2 queues -


This is a homework question and I do not know if my code is true or false Question: How can I print stacks ( So know whether the code is working or not)? If wrong, then what should I change?

What do I have:

  class stack: def __init __ (self): self.q1 = [] self .q2 = [] DEF is empty (self): Returns self .isize () == 0 DRF pop (self): Returns self. Q 1 pop (0) DEF push (self, item): for category i (i E.) (self). : Self.q2.append (self.q1.pop) self.q2 = self.q1 print (self.q1) s = stack () s.push ('2') print (s)  

How do I print a stack?

A clear possibility, which does not rely solely on your implementation (which makes it a great unit test): Just s.pop () See it until it fails:

  while correct: try: print except index (s.pop ()): break  

But what if you want to do a non-destructive test? Okay, there are two options.


First of all, staying with the "black box" approach, if you believe that push works properly, then you can take advantage of it a copy What should a stack do to print a stack when creating:

  s2 = stack () while correct: try: value = s.pop () except indexError: break Other: Print (value) s2.push (value)  

Definitely gives you a reverse stack, so you have to loop it again, S2 back s :

  while correct: try: value = s2.pop () s.push (value): Inverted error: Pause Second, you can switch to a white box approach. What does  pop  do? Well, it gives the final value in  q1 , and removes it, so if you repeatedly call  pop , then it will only reverse order the  Q1 is going to return the value in . Therefore: 

  back in value (s.q1): print (value)  

But if you run any of these You have to 'see again that the stack is always empty. Why? OK, let's your push :

  def Push (self, item): i. (I Q1): self.q2.append (self.q1.pop)  

OK, the first problem is here: you call Forget forgot to pop here, so instead of popping up the value and adding the result, simply add the method self.q1.pop .

  itself Q2 = self.q1  

and here, you have to go from q1 to q2 You have done all this work to move values, and then you can replace q2 - which has all your values ​​- with q1 - which is empty.

But, even if you fix it, then what is q1 actually doing? It always remains empty in the beginning; it always remains empty after push it is always smaller after a pop , so there is probably nothing in it, so clearly From, you have a basic problem with your design, and there is no way to fix the implementation of a broken design.


Comments