Consider the following function, which returns all unique permutations of a set of elements:
def get_permutations(elements): if len(elements) == 0: yield () else: unique_elements = set(elements) for first_element in unique_elements: remaining_elements = list(elements) remaining_elements.remove(first_element) for subpermutation in get_permutations(tuple(remaining_elements)): yield (first_element,) + subpermutation for permutation in get_permutations((1, 1, 2)): print(permutation)
Will print
(1, 1, 2) (1, 2, 1) (2, 1, 1)
as was expected. However, when I add the lru_cache decorator , which remembers the function:
import functools @functools.lru_cache(maxsize=None) def get_permutations(elements): if len(elements) == 0: yield () else: unique_elements = set(elements) for first_element in unique_elements: remaining_elements = list(elements) remaining_elements.remove(first_element) for subpermutation in get_permutations(tuple(remaining_elements)): yield (first_element,) + subpermutation for permutation in get_permutations((1, 1, 2)): print(permutation)
he prints the following:
(1, 1, 2)
Why is this just the seal of the first permutation?
lru.cache . . (.. ). , LRU - , . , !
lru.cache
, , , . ( " " .)
, , , elements 0, yield ()... . , , . , subpermutation , . , , , .
elements
yield ()
(1,) , , ().
(1,)
()
, , print(elements) ( - print for, ). memoized .
print(elements)
print
for
, , , - . , , , ( , ts ) memoize.