Error while writing a list in reverse order using stack

python stack

58 观看

2回复

35 作者的声誉

I wrote this program to print elements in a list in reverse order. It's giving me the correct answer, but it shows another error after the answer. What's wrong with my code?

Stack Class

class Stack:
  def __init__(self):
    self.items=[]

  def isEmpty(self):
    return self.items==[]

  def push(self,data):
    self.items.append(data)

  def size(self):
    return len(Self.items)

  def show(self):
    print (self.items)

  def peek(self):
    return self.items[len(self.items)-1]

  def pop(self):
    assert not self.isEmpty()
    return self.items.pop()

Program

def reverseOrder():
    lista = [1,4,6,7,8,9]
    s = Stack()

    for i in lista:
        s.push(i)

    while s.isEmpty:
        print(s.pop())

reverseOrder()

and following is my output:

>>> 
 RESTART: C:/Users/Dil/AppData/Local/Programs/Python/Python36-32/Tutorials/reverseOrder.py 
9
8
7
6
4
1
Traceback (most recent call last):
  File "C:/Users/Dil/AppData/Local/Programs/Python/Python36-32/Tutorials/reverseOrder.py", line 35, in <module>
    reverseOrder();
  File "C:/Users/Dil/AppData/Local/Programs/Python/Python36-32/Tutorials/reverseOrder.py", line 33, in reverseOrder
    print(s.pop());
  File "C:/Users/Dil/AppData/Local/Programs/Python/Python36-32/Tutorials/reverseOrder.py", line 21, in pop
    assert not self.isEmpty()
AssertionError
>>> 
作者: dilk 的来源 发布者: 2017 年 9 月 15 日

回应 2


2

794 作者的声誉

while s.isEmpty():
    print(s.pop())

This should be

while not s.isEmpty():
    print(s.pop())

Remove elements from stack while it is not empty.

作者: Aanchal1103 发布者: 2017 年 9 月 15 日

1

2154 作者的声誉

决定

Well, everything works just as You wrote it :-). assert command do as it name says, it asserts some condition. If condition is meet, everything is fine. If it's not, it raises an error. What You need instead of assert is:

def pop(self):
    if not self.isEmpty():
        return self.items.pop()

But, since You already check that list is not empty in while loop, You should leave this out, so it should be like:

def pop(self):
    return self.items.pop()

As others have suggested, instead of

while s.isEmpty():

You should use

while not s.isEmpty(): 
作者: Fejs 发布者: 2017 年 9 月 15 日
32x32