@lru_cache on function with commutative arguments

227 views Asked by At

I am calculating the Hamming distance between 2 strings where Hamming(A,B) == Hamming(B,A)

The function signature is

@lru_cache
def Hamming(A:str,B:str)->int:
    ...

How can I modify @lru_cache or the function to ignore argument order when indexing into the cache?

2

There are 2 answers

2
user2390182 On

You can insert an extra function call that predictably rearranges the arguments:

def Hamming(A: str, B: str) -> int:
    if B < A:
        A, B = B, A
    return _Hamming(A, B) 

@lru_cache
def _Hamming(A, B):
    ...
0
Greedo On

Another option:

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:
    ...

Or in general:

@cached(cache={}, key=lambda *args: hashkey(tuple(sorted(args))))
def Hamming(A: str, B: str) -> int:
    ...