Implementing Stack with Python

前端 未结 12 1079
长发绾君心
长发绾君心 2021-01-17 16:16

I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what\'s wrong with my code.

class myStack:
            


        
12条回答
  •  醉梦人生
    2021-01-17 16:58

    I left a comment with the link to http://docs.python.org/2/tutorial/datastructures.html#using-lists-as-stacks, but if you want to have a custom type that gives you push, pop, is_empty, and size convenience methods, I'd just subclass list.

    class Stack(list):
        def push(self, item):
            self.append(item)
        def size(self):
            return len(self)
        def is_empty(self):
            return not self
    

    However, as I said in the comments, I'd probably just stick with a straight list here, as all you are really doing is aliasing existing methods, which usually only serves to make your code harder to use in the long run, as it requires people using it to learn your aliased interface on top of the original.

提交回复
热议问题