Can you do xor in python?

Some of the implementations suggested here will cause repeated evaluation of the operands in some cases, which may lead to unintended side effects and therefore must be avoided.

That said, a xor implementation that returns either True or False is fairly simple; one that returns one of the operands, if possible, is much trickier, because no consensus exists as to which operand should be the chosen one, especially when there are more than two operands. For instance, should xor(None, -1, [], True) return None, [] or False? I bet each answer appears to some people as the most intuitive one.

For either the True- or the False-result, there are as many as five possible choices: return first operand (if it matches end result in value, else boolean), return first match (if at least one exists, else boolean), return last operand (if ... else ...), return last match (if ... else ...), or always return boolean. Altogether, that's 5 ** 2 = 25 flavors of 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 Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are identical XOR outputs as 0 and when two bits are different then XOR outputs as 1. XOR can even be used on booleans.

XOR is mainly used in situations where we don’t want two conditions to be true simultaneously. In this tutorial, we will look explore multiple ways to perform XOR (exclusive OR) operations in Python with examples.

Bitwise Operator

Bitwise operators in Python are also called binary operators, and it is mainly used to perform Bitwise calculations on integers, the integers are first converted into binary, and later the operations are performed bit by bit.

Python XOR Operator

Let’s take a look at using the XOR Operator between 2 integers. When we perform XOR between 2 integers, the operator returns the integer as output.

a= 5 #0101 b = 3 #0011 result = (a ^ b) #0110 print(result) # Output # 6 (0110)

Let’s take a look at using XOR on two booleans. In the case of boolean, the true is treated as 1, and the false is treated as 0. Thus the output returned will be either true or false.

print(True ^ True) print(True ^ False) print(False ^ True) print(False ^ False)

Output

False True True False

XOR using Operator Module

We can even achieve XOR using the built-in operator module in Python. The operator module has a xor() function, which can perform an XOR operation on integers and booleans, as shown below.

import operator print(operator.xor(5,3)) print(operator.xor(True,True)) print(operator.xor(True,False)) print(operator.xor(False,True)) print(operator.xor(False,False))

Output

6 False True True False

Related Tags
  • Bitwise Operator,
  • exclusive or,
  • operator,
  • XOR

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Does XOR work in Python?

In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators. ... Bitwise operators..

How do you make an XOR in Python?

The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1. Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations. For example, when used between two integers, the XOR operator returns an integer.

How do you find the XOR value in Python?

To get the logical xor of two or more variables in Python: Convert inputs to booleans. Use the bitwise xor operator ( ^ or operator. xor ).
That's 100 ns of my life I won't get back ;-) ... .
For an in-between timing, you can do from operator import truth at the top of the module, and test truth(a) !=.

Is XOR a Boolean operator in Python?

XOR Operator in Python is also known as “exclusive or” that compares two binary numbers bitwise if two bits are identical XOR outputs as 0 and when two bits are different then XOR outputs as 1. XOR can even be used on booleans.

Chủ đề