Python CookBook(self report)

Python CookBook

中文版:https://python3-cookbook.readthedocs.io/zh_CN/latest/copyright.html

英文版:https://d.cxcore.net/Python/Python_Cookbook_3rd_Edition.pdf

Data Structures and Algorithms

start expressions

复制代码
items = [1, 10, 7, 4, 5, 9] 
def sum(items):
... head, *tail = items
... return head + sum(tail) if tail else head
...
>>> head, *tail = items
>>> head
1
>>> tail
[10, 7, 4, 5, 9]
>>> sum(items)
36
复制代码

Deque

Using deque(maxlen=N) creates a fixed-sized queue. When new items are added and the queue is full, the oldest item is automatically removed. 

复制代码
from collections import deque
>>> q = deque(maxlen=3) >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q deque([1, 2, 3], maxlen=3) >>> q.append(4) >>> q

deque([1, 2, 3])
>>> q.appendleft(4)
>>> q deque([4, 1, 2, 3])
>>> q.pop() 3
>>> q deque([4, 1, 2])
>>> q.popleft() 4  
复制代码

★ Adding or popping items from either end of a queue has O(1) complexity. This is unlike a list where inserting or removing items from the front of the list is O(N).

Heapq

复制代码
The heapq module has two functions—nlargest() and nsmallest()—that do exactly what you want. For example:
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
Both functions also accept a key parameter that allows them to be used with more
complicated data structures. For example:
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'])
复制代码

 

 

 

 

 

 

 

 

 

 

 

 

声明:如果涉及侵权请联系本人‘删除’,谢谢~
posted @    ̄□ ̄  阅读(403)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示