Logical NAND of two variables in Python

Viewed 25063

I'm making a function that makes 50 random trees in a 1000 by 1000 area.

I need to make sure that Tree 2's x and y both are not the same as Tree 1's x and y. This takes a NAND Gate. I'm okay with one of them being the same, I'm okay with neither being the same, but not with both being the same. I can't seem to find anything about making NAND Gates in python. I'm fine with defining a function to make a NAND.

4 Answers

Equivalently, you can also use ~(a&b)+2, though I'm not sure why you would prefer it:

opts = [(0,0),(0,1),(1,0),(1,1)]
[print(f"{a} NAND {b} = {~(a&b)+2}") for a,b in opts]
0 NAND 0 = 1
0 NAND 1 = 1
1 NAND 0 = 1
1 NAND 1 = 0

This will provide all six logic gate functions (including nand) in a dictionary:

from operator import and_, or_, xor

gates = {g.__name__.rstrip('_'): g for g in (and_, or_, xor)}
gates = {**gates, **{f'n{k}': lambda a, b, _f=v: _f(a, b) ^ True for k, v in gates.items()}}

x ^ y means xor(x, y). x ^ True means xor(x, True) which means not x.

Usage
>>> gates
{'and': <function _operator.and_(a, b, /)>,
 'or': <function _operator.or_(a, b, /)>,
 'xor': <function _operator.xor(a, b, /)>,
 'nand': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function and_>)>,
 'nor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function or_>)>,
 'nxor': <function __main__.<dictcomp>.<lambda>(a, b, _f=<built-in function xor>)>}

>>> gates['and'](True, True)
True

>>> gates['and'](1, 1)
1

>>> gates['nand'](True, True)
False

>>> gates['nand'](1, 1)
0
Related