【发布时间】:2016-08-16 15:55:00
【问题描述】:
考虑以下函数,它返回一组元素的所有唯一排列:
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)
打印出来
(1, 1, 2)
(1, 2, 1)
(2, 1, 1)
正如预期的那样。但是,当我添加 lru_cache 装饰器时,它会记住函数:
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)
它打印以下内容:
(1, 1, 2)
为什么只打印第一个排列?
【问题讨论】:
标签: python python-3.x caching higher-order-functions functools