So, inspired by this other code review, I wanted to see if I could implement a very basic stack without the linked-list approach taken by the OP in their implementation.
To that end, I came up with the following Stack class. I wrote it for Python 3, but it actually works as-is in Python 2 as well:
class Stack: _stack =  def __init__(self): self._stack =  @property def size(self): return len(self._stack) @property def count(self): return self.size def __sizeof__(self): return self.size def pop(self): if self.size == 0: return "Cannot pop from an empty stack." item = self._stack[self.size - 1] self._stack.remove(item) return item def peek(self): if self.size == 0: return "Cannot peek into an empty stack." return self._stack[self.size - 1] def push(self, item): self._stack.append(item) def __iter__(self): return iter(self._stack)
I'm probably missing some key parts of what one would want from a Stack, but any improvement is welcome. Literally any improvement.
Note there were a couple things I did intentionally:
- I intentionally initialize the _stack attribute as an empty list both in the class itself and in
__init__. For some reason PyCharm complains if the attribute isn't already part of the class when being worked with in
__init__, so this is more or less to get PyCharm to stop yelling at me.
- I intentionally have
__sizeof__declared as referring to the
sizeproperty function. This lets
len(StackObject)work if someone doesn't want to do
With these in mind, feel free to tell me what you think, or point out any mistakes I've made. (I'm not an expert in data structures, so I may have gotten some points messed up a little).