首页 > 编程语言 > 详细

Python CookBook——数据结构和算法

时间:2019-05-04 19:20:15      阅读:129      评论:0      收藏:0      [点我收藏+]

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——数据结构和算法

原文:https://www.cnblogs.com/tomoka/p/10809355.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!