Python3 basic learning-June 16, 2023-combinations

combinations

https://docs.python.org/zh-cn/3/library/itertools.html#itertools.combinations
returns a subsequence of length r composed of elements in the input iterable.

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

akin
insert image description here

lru_cache

A decorator that provides a cache function for the function, caches the maxsize group of incoming parameters, and returns the previous result directly when it is called next time with the same parameters. It is used to save the call time of high overhead or I/O functions.
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)))


When not adding the optimized results

5
4
3
2
1
0
1
2
1
0
3
2
1
0
1
输出:5

The output after optimization

5
4
3
2
1
0
输出:5

Guess you like

Origin blog.csdn.net/JianShengShuaiest/article/details/131245373