1. 程式人生 > >Python CookBook——數據結構和算法

Python CookBook——數據結構和算法

arch import 嵌套 lec all p s pat lines 3.2

1. 解壓變量

1. 最簡單的變量解壓

data = [ ACME, 50, 91.1, (2012, 12, 21) ]
name, _, price, date = data

2. 需要一個變量接收多個值

s = [1,2,3,4,5]
a, *b, c = s
>>> a為1; b為[2,3,4]; c為5.

3. 存在嵌套的情況

record = (ACME, 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = record

2. 優先隊列與Top-K

1. FIFO隊列

使用deque實現長度為n的FIFO隊列。 deque(maxlen=N) 會創建一個大小為N的FIFO隊列。

deque有如下函數: append、appendleft、pop、popleft。

from collections import deque

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)

這裏使用生成器函數可使搜索過程代碼和使用搜索結果代碼解耦。

2. TOP-K

1. top-1

通常采用min、max函數求得最大/小值。

2. top-k

通常采用nlargest、nsmallest函數

portfolio = [
    {name: IBM, shares: 100, price: 91.1},
    {name: AAPL, shares: 50, price: 543.22},
    {name: FB, shares: 200, price: 21.09},
    {name: HPQ
, shares: 35, price: 31.75}, {name: YHOO, shares: 45, price: 16.35}, {name: ACME, shares: 75, price: 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s[price]) expensive = heapq.nlargest(3, portfolio, key=lambda s: s[price])

3. 堆數組

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
import heapq
heap = list(nums)
heapq.heapify(heap)
heap
>>> [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
# 彈出堆頂元素
heapq.heappop(heap)

4. 優先隊列

import heapq

class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]

-priority 使元素優先級從高到低排列, index 保障了優先級相同的元素按照插入先後順序排列。

3. 字典

Python CookBook——數據結構和算法