这里建议的一些实现在某些情况下会导致操作数的重复求值,这可能会导致意想不到的副作用,因此必须避免。
也就是说,一个返回True或False的xor实现相当简单;如果可能的话,返回其中一个操作数的方法要棘手得多,因为对于应该选择哪个操作数没有共识,特别是当有两个以上的操作数时。例如,xor(None, -1, [], True)是否应该返回None,[]或False?我敢打赌,每个答案对某些人来说都是最直观的。
对于True-或false -结果,有多达五种可能的选择:返回第一个操作数(如果它在value中匹配最终结果,否则布尔值),返回第一个匹配(如果至少存在一个,否则布尔值),返回最后一个操作数(如果…Else…),返回最后一次匹配(if…Else…),或者总是返回boolean。总共是5 ** 2 = 25种xor口味。
def xor(*operands, falsechoice = -2, truechoice = -2):
"""A single-evaluation, multi-operand, full-choice xor implementation
falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match"""
if not operands:
raise TypeError('at least one operand expected')
choices = [falsechoice, truechoice]
matches = {}
result = False
first = True
value = choice = None
# avoid using index or slice since operands may be an infinite iterator
for operand in operands:
# evaluate each operand once only so as to avoid unintended side effects
value = bool(operand)
# the actual xor operation
result ^= value
# choice for the current operand, which may or may not match end result
choice = choices[value]
# if choice is last match;
# or last operand and the current operand, in case it is last, matches result;
# or first operand and the current operand is indeed first;
# or first match and there hasn't been a match so far
if choice < -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice > 1 and value not in matches):
# store the current operand
matches[value] = operand
# next operand will no longer be first
first = False
# if choice for result is last operand, but they mismatch
if (choices[result] == -1) and (result != value):
return result
else:
# return the stored matching operand, if existing, else result as bool
return matches.get(result, result)
testcases = [
(-1, None, True, {None: None}, [], 'a'),
(None, -1, {None: None}, 'a', []),
(None, -1, True, {None: None}, 'a', []),
(-1, None, {None: None}, [], 'a')]
choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'}
for c in testcases:
print(c)
for f in sorted(choices.keys()):
for t in sorted(choices.keys()):
x = xor(*c, falsechoice = f, truechoice = t)
print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x))
print()