Python好庫

gebeng發表於2024-03-24

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))

相關文章