Why does functools.lru_cache function violate this function?

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?

+4
source share
1 answer

lru.cache . . (.. ). , LRU - , . , !

, , , . ( " " .)

, , , elements 0, yield ()... . , , . , subpermutation , . , , , .

(1,) , , ().

, , print(elements) ( - print for, ). memoized .

, , , - . , , , ( , ts ) memoize.

+9

All Articles