from __future__ import print_function__author__ = 'Omkar Pathak'class Stack(object):""" A stack is an abstract data type that serves as a collection ofelements with two principal operations: push() and pop(). push() adds anelement to the top of the stack, and pop() removes an element from the topof a stack. The order in which elements come off of a stack areLast In, First Out (LIFO).https://en.wikipedia.org/wiki/Stack_(abstract_data_type)"""def __init__(self, limit=10):self.stack = []self.limit = limitdef __bool__(self):return bool(self.stack)def __str__(self):return str(self.stack)def push(self, data):""" Push an element to the top of the stack."""if len(self.stack) >= self.limit:raise StackOverflowErrorself.stack.append(data)def pop(self):""" Pop an element off of the top of the stack."""if self.stack:return self.stack.pop()else:raise IndexError('pop from an empty stack')def peek(self):""" Peek at the top-most element of the stack."""if self.stack:return self.stack[-1]def is_empty(self):""" Check if a stack is empty."""return not bool(self.stack)def size(self):""" Return the size of the stack."""return len(self.stack)class StackOverflowError(BaseException):passif __name__ == '__main__':stack = Stack()for i in range(10):stack.push(i)print('Stack demonstration:\n')print('Initial stack: ' + str(stack))print('pop(): ' + str(stack.pop()))print('After pop(), the stack is now: ' + str(stack))print('peek(): ' + str(stack.peek()))stack.push(100)print('After push(100), the stack is now: ' + str(stack))print('is_empty(): ' + str(stack.is_empty()))print('size(): ' + str(stack.size()))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。