Files
hello-algo/en/codes/python/chapter_stack_and_queue/array_stack.py
T
Yudong Jin 2778a6f9c7 Translate all code to English (#1836)
* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
2025-12-31 07:44:52 +08:00

73 lines
1.7 KiB
Python

"""
File: array_stack.py
Created Time: 2022-11-29
Author: Peng Chen (pengchzn@gmail.com)
"""
class ArrayStack:
"""Stack based on array implementation"""
def __init__(self):
"""Constructor"""
self._stack: list[int] = []
def size(self) -> int:
"""Get the length of the stack"""
return len(self._stack)
def is_empty(self) -> bool:
"""Check if the stack is empty"""
return self.size() == 0
def push(self, item: int):
"""Push"""
self._stack.append(item)
def pop(self) -> int:
"""Pop"""
if self.is_empty():
raise IndexError("Stack is empty")
return self._stack.pop()
def peek(self) -> int:
"""Access top of the stack element"""
if self.is_empty():
raise IndexError("Stack is empty")
return self._stack[-1]
def to_list(self) -> list[int]:
"""Return list for printing"""
return self._stack
"""Driver Code"""
if __name__ == "__main__":
# Initialize stack
stack = ArrayStack()
# Elements push onto stack
stack.push(1)
stack.push(3)
stack.push(2)
stack.push(5)
stack.push(4)
print("stack =", stack.to_list())
# Access top of the stack element
peek: int = stack.peek()
print("Top of the stack element peek =", peek)
# Element pop from stack
pop: int = stack.pop()
print("Popped element pop =", pop)
print("After pop stack =", stack.to_list())
# Get the length of the stack
size: int = stack.size()
print("Length of the stack size =", size)
# Check if it is empty
is_empty: bool = stack.is_empty()
print("Is the stack empty =", is_empty)