class StackOverflowError(BaseException):passclass Stack:"""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: int = 10):self.stack = []self.limit = limitdef __bool__(self) -> bool:return bool(self.stack)def __str__(self) -> str: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."""return self.stack.pop()def peek(self):""" Peek at the top-most element of the stack."""return self.stack[-1]def is_empty(self) -> bool:""" Check if a stack is empty."""return not bool(self.stack)def is_full(self) -> bool:return self.size() == self.limitdef size(self) -> int:""" Return the size of the stack."""return len(self.stack)def __contains__(self, item) -> bool:"""Check if item is in stack"""return item in self.stackdef test_stack() -> None:""">>> test_stack()"""stack = Stack(10)assert bool(stack) is Falseassert stack.is_empty() is Trueassert stack.is_full() is Falseassert str(stack) == "[]"try:_ = stack.pop()assert False # This should not happenexcept IndexError:assert True # This should happentry:_ = stack.peek()assert False # This should not happenexcept IndexError:assert True # This should happenfor i in range(10):assert stack.size() == istack.push(i)assert bool(stack) is Trueassert stack.is_empty() is Falseassert stack.is_full() is Trueassert str(stack) == str(list(range(10)))assert stack.pop() == 9assert stack.peek() == 8stack.push(100)assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])try:stack.push(200)assert False # This should not happenexcept StackOverflowError:assert True # This should happenassert stack.is_empty() is Falseassert stack.size() == 10assert 5 in stackassert 55 not in stackif __name__ == "__main__":test_stack()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。