Python好库

Python好库

一、有序列表

from sortedcontainers import SortedList

sl = SortedList([1,3])
sl.add(-1)
sl.remove(3)
print(sl)
print(sl.bisect_left(1))
print(sl.bisect_right(3))
"""
SortedList([-1, 1])
1
2
"""

二、排列组合

from itertools import permutations,combinations,combinations_with_replacement

a = [1,2,3,4,5]

# 排列
b = list(permutations(a,2))
print(b)
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]

# 组合
c = list(combinations(a,4))
print(c)
# [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

# 允许同一个元素被选择多次
d = list(combinations_with_replacement(a,2))
print(d)
# [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]

三、缓存装饰器【记忆化搜索神器】

import sys
sys.setrecursionlimit(1000000)
from functools import lru_cache

@lru_cache(None)
def dfs(x):
    if x <= 1:
        return 1
    return dfs(x - 1) + dfs(x - 2)

print(dfs(1000))
posted @ 2024-03-24 21:51  gebeng  阅读(27)  评论(0)    收藏  举报