问题描述
我正在计算 2 个字符串之间的汉明距离,其中 Hamming(A,B) == Hamming(B,A)
函数签名是
@lru_cache
def Hamming(A:str,B:str)->int:
...
如何修改@lru_cache 或在索引到缓存时忽略参数顺序的函数?
解决方法
您可以插入一个额外的函数调用来可预测地重新排列参数:
def Hamming(A: str,B: str) -> int:
if B < A:
A,B = B,A
return _Hamming(A,B)
@lru_cache
def _Hamming(A,B):
...
,
另一种选择:
from cachetools import cached
from cachetools.keys import hashkey
@cached(cache={},key=lambda A,B: hashkey((A,B) if A < B else (B,A)))
def Hamming(A: str,B: str) -> int:
...
或者一般来说:
@cached(cache={},key=lambda *args: hashkey(tuple(sorted(args))))
def Hamming(A: str,B: str) -> int:
...