combinations
https://docs.python.org/zh-cn/3/library/itertools.html#itertools.combinations
返回由输入 iterable 中元素组成长度为 r 的子序列。
from itertools import combinations
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = combinations(a, 2)
print(list(b))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
类似的
lru_cache
一个为函数提供缓存功能的装饰器,缓存 maxsize 组传入参数,在下次以相同参数调用时直接返回上一次的结果。用以节约高开销或I/O函数的调用时间。
https://docs.python.org/zh-cn/3/library/functools.html#functools.lru_cache
from functools import lru_cache
from itertools import combinations
@lru_cache(maxsize=None)
def fibonacci(n):
print(n)
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = combinations(a, 2)
print(list(b))
print("输出:{0}".format(fibonacci(5)))
当不加入优化的结果
5
4
3
2
1
0
1
2
1
0
3
2
1
0
1
输出:5
优化之后的输出结果
5
4
3
2
1
0
输出:5