如何在Python中获得两个变量的逻辑异或?

例如,我有两个变量,我希望它们是字符串。我想测试它们中只有一个包含True值(不是None或空字符串):

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

^操作符似乎是按位的,并不是在所有对象上都定义:

>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

当前回答

这里建议的一些实现在某些情况下会导致操作数的重复求值,这可能会导致意想不到的副作用,因此必须避免。

也就是说,一个返回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()

其他回答

这里建议的一些实现在某些情况下会导致操作数的重复求值,这可能会导致意想不到的副作用,因此必须避免。

也就是说,一个返回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()

如果已经将输入规范化为布尔值,则!= = xor。

bool(a) != bool(b)

这就是我编写真值表的方法。对于xor,我们有:

| a | b  | xor   |             |
|---|----|-------|-------------|
| T | T  | F     |             |
| T | F  | T     | a and not b |
| F | T  | T     | not a and b |
| F | F  | F     |             |

看看答案列中的T值,用逻辑上的或将所有真情况串在一起。所以,这个真值表可以在情况2或3中产生。因此,

xor = lambda a, b: (a and not b) or (not a and b)

这个怎么样?

(not b and a) or (not a and b)

如果b为假会给出a 如果a为假,会给出b 否则会返回False

或者使用Python 2.5+三元表达式:

(False if a else b) if b else a

我已经测试了几种方法(包括使用shadow wranger建议的truth()函数)。

%timeit  (not a) ^  (not b)   # 47 ns
%timeit  (not a) != (not b)   # 44.7 ns
%timeit truth(a) != truth(b)  # 116 ns
%timeit  bool(a) != bool(b)   # 190 ns