import math def pair_distance(a, b, box): d = [x - y for x, y in zip(a, b)] d = [v - box * math.floor(v / box + 0.5) for v in d] return math.hypot(*d)