Python中两个变量的逻辑非运算

11

我正在编写一个函数,用于在 1000 x 1000 的区域内创建 50 棵随机树。

我需要确保第二棵树的 x 和 y 坐标都不与第一棵树的 x 和 y 坐标相同。这需要一个 NAND 门。我不介意其中一个坐标相同,也不介意两个坐标都不同,但不能同时相同。我似乎找不到任何关于在 Python 中创建 NAND 门的信息。我可以定义一个函数来制作 NAND。


4
“def nand(a, b): return not (a and b)” 有什么问题吗? - Henry Keiter
我认为句子“Tree 2的x和y都与Tree 1的x和y不同”是“both”的错误(且无意义)使用。 - Eric
4个回答

28

NAND是and的否定。

not (a and b) 

应该完全可行,以a和b为输入,或者我有什么地方理解不对吗?


7
翻译为中文:

解释:

树2的x和y坐标与树1的x和y坐标不相同

改为:

树2的x和y坐标不同时与树1的x和y坐标相同

return (t1.x, t1.y) != (t2.x, t2.y)

0

这将在字典中提供所有六个逻辑门函数(包括nand):

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 表示 xor(x, y)x ^ True 表示 xor(x, True),这意味着 not x

用法
>>> 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

0

等价地,您也可以使用~(a&b)+2,不过我不确定为什么您会更喜欢它:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接