数据结构/算法 | 语言内置 | 内置库 |
---|---|---|
线性结构 | list(列表)/tuple(元祖) | array(数组,不经常使用)/collection.namedtuple |
链式结构 | collections.deque(双端队列) | |
字典结构 | dict(字典) | collections.Counter(计数器)/OrderedDict(有序字典) |
集合结构 | set(集合)/frozenset(不可变集合) | |
排序算法 | sorted | |
二分算法 | bisect模块 | |
堆算法 | heapq模块 | |
缓存算法 | functors.lru_cache(Least Recent Used,python3) |
coolections模块提供了一些内置数据结构的扩展node
collections Point = collections.namedtuple('Point','x','y') p = Point(1,2)
namedtuple让tuple属性可读python
de = collections.deque() de.append(1) de.appendleft(0)
c = collections.Counter() c = coolections.Counter('abcab')
python dict 底层结构web
t = ([1],2,3) t[0].append(1) t ([1,1],2,3) 保存的引用不可变指的是你无法替换掉这个对象,可是若是对系那个自己是一个可变对象,是能够修改这个引用指向的可变对象的
Least-Recently-Used 替换掉最近最少使用的对象算法
字典用来缓存,循环双端链表用来记录访问顺序后端
from collections import OrderedDict class LRUCache: def __init__(self, capacity=128): self.od = OrderedDict() self.capacity = capacity def get(self, key): #每次访问更新最新使用的key if key in self.od: val = self.od[key] self.od.move_to_end(key) return val else: return -1 def put(self, key, value): # 更新k/v if key in self.od: del self.od[key] self.od[key] = value # 更新key 到表头 else: # insert self.od[key] = value # 判断当前容量是否已经满了 if len(self.od) > self.capacity: self.od.popitem(last=False) code/lrucache.py
排序+查找,重中之重数组
python web 后端常考数据结构缓存
常考数据结构之链表数据结构
链表有单链表、双链表、循环双链表app
数据结构之链表数据结构和算法
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: pre = None cur = head while cur: nextnode = cur.next cur.next = pre pre = cur cur = nextnode ruture pre
队列(queue)是先进先出结构
from collections import deque class Queue: def __init__(self): self.items = deque() def append(self, val): retuen self.items.append(val) def pop(self): return self.items.popleft() def empty(self): return len(self.items) == 0 def test_queue(): q = Queue() q.append(0) q.append(1) q.append(2) print(q.pop()) print(q.pop()) print(q.pop()) test_queue()() 0 1 2
栈(stack)是后进先出结构
from collections import deque class Stack(object): def __init__(self): self.deque = deque() # 或者用list def push(self, value): self.deque.append(value) def pop(self): return self.deque.pop()
一个常考问题: 如何用两个栈实现队列?
python dict/set 底层都是哈希表