我正在寻找一种方法来检查2个排列(由列表表示)是否与相同parity 。请注意,我对它们是否是偶数或奇数奇偶性不感兴趣,而只是对它们相等。
我是Python的新手,下面给出了我的幼稚解决方案作为答复。我期待Python专家向我展示一些很酷的技巧,以更少,更优雅的Python代码实现相同的目的。
最佳答案
先前答案的一个较小变体-复制perm1,并保存数组查找。
def arePermsEqualParity(perm0, perm1):
"""Check if 2 permutations are of equal parity.
Assume that both permutation lists are of equal length
and have the same elements. No need to check for these
conditions.
"""
perm1 = perm1[:] ## copy this list so we don't mutate the original
transCount = 0
for loc in range(len(perm0) - 1): # Do (len - 1) transpositions
p0 = perm0[loc]
p1 = perm1[loc]
if p0 != p1:
sloc = perm1[loc:].index(p0)+loc # Find position in perm1
perm1[loc], perm1[sloc] = p0, p1 # Swap in perm1
transCount += 1
# Even number of transpositions means equal parity
if (transCount % 2) == 0:
return True
else:
return False