Python 列表原生 append/pop 即為堆疊操作。本文構建一個互動式選單程式,示範推入、彈出、檢視、退出四大操作,並以字典分派命令模式簡化控制流程。
#!/usr/bin/env python
stack = []
def pushit():
stack.append(input('Enter new string: ').strip())
def popit():
if not stack:
print('Cannot pop from an empty stack!')
else:
print('Removed [', stack.pop(), ']')
def viewstack():
print(stack)
CMDs = {'u': pushit, 'o': popit, 'v': viewstack}
def showmenu():
prompt = """
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = input(prompt).strip()[0].lower()
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print(f'\nYou picked: [{choice}]')
if choice not in 'uovq':
print('Invalid option, try again')
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
p(U)sh p(O)p (V)iew (Q)uit Enter choice: u Enter new string: hello You picked: [u] p(U)sh p(O)p (V)iew (Q)uit Enter choice: u Enter new string: world You picked: [u] p(U)sh p(O)p (V)iew (Q)uit Enter choice: v You picked: [v] ['hello', 'world'] p(U)sh p(O)p (V)iew (Q)uit Enter choice: o You picked: [o] Removed [ world ] p(U)sh p(O)p (V)iew (Q)uit Enter choice: q
append = push,pop() = pop (LIFO),均為 O(1) 擴展時間。CMDs[choice]() 替代冗長 if/elif,擴充新指令只需加入字典。strip()[0].lower() 統一大小寫、去除空白;try/except 捕獲 EOF/Ctrl+C/空輸入。if __name__ == '__main__': 確保模組匯入不自動執行。
class FixedStack:
def __init__(self, capacity):
self._data = []
self._capacity = capacity
def push(self, item):
if len(self._data) >= self._capacity:
raise OverflowError('Stack full')
self._data.append(item)
def pop(self):
if not self._data:
raise IndexError('Stack empty')
return self._data.pop()
def __len__(self): return len(self._data)
def __bool__(self): return bool(self._data)