萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 列表模擬堆疊 (Stack) 互動式實作

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)
copyright © 萬盛學電腦網 all rights reserved