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
def nand(a, b): return not (a and b)
?