2024年10月9日 星期三

deque 10 個簡單應用範例

 deque 10 個簡單應用範例:

from collections import deque

# 1. 最近使用的元素 (LRU Cache) 模擬
dq = deque(maxlen=3)  # 設定最大長度
dq.append('A')
dq.append('B')
dq.append('C')
print("1. LRU Cache:", dq)  # deque(['A', 'B', 'C'], maxlen=3)
dq.append('D')  # 'A' 被自動移除
print("1. After adding D:", dq)  # deque(['B', 'C', 'D'], maxlen=3)

# 2. 滑動窗口
data = [1, 2, 3, 4, 5, 6, 7, 8]
window_size = 3
dq = deque(maxlen=window_size)
for num in data:
    dq.append(num)
    print("2. Sliding window:", list(dq))
# Output for each window:
# [1], [1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8]

# 3. 回文檢查
def is_palindrome(s):
    dq = deque(s)
    while len(dq) > 1:
        if dq.popleft() != dq.pop():
            return False
    return True

print("3. Is 'radar' a palindrome?", is_palindrome("radar"))  # True
print("3. Is 'hello' a palindrome?", is_palindrome("hello"))  # False

# 4. 反轉字串
dq = deque("hello")
dq.reverse()
print("4. Reversed string:", ''.join(dq))  # "olleh"

# 5. 排列處理 (隊列模擬)
tasks = deque(["task1", "task2", "task3"])
tasks.append("task4")  # 新任務加入隊尾
print("5. Tasks:", tasks)  # deque(['task1', 'task2', 'task3', 'task4'])
tasks.popleft()  # 最早加入的任務完成,移除
print("5. After finishing one task:", tasks)  # deque(['task2', 'task3', 'task4'])

# 6. 動態歷史記錄
history = deque(maxlen=5)  # 保留最近5個操作
for i in range(1, 8):
    history.append(f"Action {i}")
    print("6. Current history:", list(history))
# Output:
# ['Action 1'], ['Action 1', 'Action 2'], ..., ['Action 3', 'Action 4', 'Action 5', 'Action 6', 'Action 7']

# 7. 當前網站瀏覽紀錄 (回退功能)
websites = deque()
websites.append("google.com")
websites.append("stackoverflow.com")
websites.append("github.com")
print("7. Current site:", websites[-1])  # "github.com"
websites.pop()  # 回退到上個網站
print("7. After going back:", websites[-1])  # "stackoverflow.com"

# 8. 動態數據流處理 (只保留最新數據)
stream = deque(maxlen=5)
for i in range(10):
    stream.append(i)
    print(f"8. Stream after {i}: {stream}")
# Output for each step:
# deque([0], maxlen=5), ..., deque([5, 6, 7, 8, 9], maxlen=5)

# 9. 隊列實現的固定大小記錄系統
log = deque(maxlen=3)
log.append("Error 1")
log.append("Error 2")
log.append("Error 3")
print("9. Log:", log)  # deque(['Error 1', 'Error 2', 'Error 3'], maxlen=3)
log.append("Error 4")  # 超過最大長度時,最早的會被移除
print("9. After new error:", log)  # deque(['Error 2', 'Error 3', 'Error 4'], maxlen=3)

# 10. 瀑布模型的步驟追蹤
steps = deque(["Step 1", "Step 2", "Step 3"])
steps.append("Step 4")
steps.appendleft("Initialization")
print("10. Process steps:", steps)  # deque(['Initialization', 'Step 1', 'Step 2', 'Step 3', 'Step 4'])

執行結果:

  1. 最近使用的元素 (LRU Cache)

    1. LRU Cache: deque(['A', 'B', 'C'], maxlen=3)
    1. After adding D: deque(['B', 'C', 'D'], maxlen=3)
    
  2. 滑動窗口

    2. Sliding window: [1]
    2. Sliding window: [1, 2]
    2. Sliding window: [1, 2, 3]
    ...
    2. Sliding window: [6, 7, 8]
    
  3. 回文檢查

    3. Is 'radar' a palindrome? True
    3. Is 'hello' a palindrome? False
    
  4. 反轉字串

    4. Reversed string: olleh
    
  5. 排列處理 (隊列模擬)

    5. Tasks: deque(['task1', 'task2', 'task3', 'task4'])
    5. After finishing one task: deque(['task2', 'task3', 'task4'])
    
  6. 動態歷史記錄

    6. Current history: ['Action 1']
    6. Current history: ['Action 1', 'Action 2']
    ...
    6. Current history: ['Action 3', 'Action 4', 'Action 5', 'Action 6', 'Action 7']
    
  7. 網站瀏覽紀錄 (回退功能)

    7. Current site: github.com
    7. After going back: stackoverflow.com
    
  8. 動態數據流處理

    8. Stream after 0: deque([0], maxlen=5)
    8. Stream after 1: deque([0, 1], maxlen=5)
    ...
    8. Stream after 9: deque([5, 6, 7, 8, 9], maxlen=5)
    
  9. 固定大小記錄系統

    9. Log: deque(['Error 1', 'Error 2', 'Error 3'], maxlen=3)
    9. After new error: deque(['Error 2', 'Error 3', 'Error 4'], maxlen=3)
    
  10. 瀑布模型步驟追蹤

10. Process steps: deque(['Initialization', 'Step 1', 'Step 2', 'Step 3', 'Step 4'])

沒有留言:

張貼留言