棧
后進先出(LIFO: Last In First Out)
# -.- coding:utf-8 -.-
from __future__ import print_function
def checker(func):
def wrapper(self, *args, **kwargs):
if self.empty():
return self.items
return func(self, *args, **kwargs)
return wrapper
class Stack(object):
"""棧: 有序, 后進先出"""
def __init__(self):
self.items = []
def size(self):
"""獲取棧元素總數."""
return len(self.items)
def empty(self):
"""棧為空則返回: True ; 棧非空返回: False"""
return not self.size()
def append(self, item):
"""在棧的最末端增加一個元素."""
self.items.append(item)
return self.items
@checker
def peek(self):
"""在棧的最末端獲取一個元素, 不做移除動作."""
return self.items[-1]
@checker
def get(self):
"""在棧的最末端獲取一個元素, 并移除該元素."""
return self.items.pop()
def __iter__(self):
"""讓棧支持迭代"""
return self
def __next__(self):
"""Python3: 讓棧支持for循環"""
if not self.empty():
return self.get()
raise StopIteration
def next(self):
"""Python2: 讓棧支持for循環"""
return self.__next__()
def __str__(self):
"""讓棧支持print打印結果"""
return "{}".format(self.items)
if __name__ == '__main__':
# 創建一個棧對象.
stack = Stack()
# 為棧對象增加幾個元素
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
# 查看棧對象
print("查看棧對象: ", stack)
# 獲取棧對象的一個元素
print("獲取棧對象的一個元素: ", stack.get())
# 查看棧對象
print("查看棧對象: ", stack)
# 遍歷棧對象
for enum, i in enumerate(stack):
print("遍歷第{}個元素: ".format(enum), i)
# 輸出結果
# 查看棧對象: ['a', 'b', 'c', 'd', 'e']
# 獲取棧對象的一個元素: e
# 查看棧對象: ['a', 'b', 'c', 'd']
# 遍歷第0個元素: d
# 遍歷第1個元素: c
# 遍歷第2個元素: b
# 遍歷第3個元素: a