【问题标题】:Logical NAND of two variables in PythonPython中两个变量的逻辑与非
【发布时间】:2013-12-17 17:09:11
【问题描述】:

我正在制作一个函数,可以在 1000 x 1000 的区域中生成 50 棵随机树。

我需要确保树 2 的 x 和 y 都与树 1 的 x 和 y 不同。这需要一个与非门。我可以接受其中一个相同,我可以接受两者都不相同,但不能接受两者相同。我似乎找不到任何关于在 python 中制作 NAND Gates 的信息。我可以定义一个函数来制作 NAND。

【问题讨论】:

  • def nand(a, b): return not (a and b)有什么问题吗?
  • 我认为句子 "Tree 2's x and y both are not the same as Tree 1's x and y" 是“both”的不正确(且无意义)放置

标签: python variables logical-operators


【解决方案1】:

由于NAND是and的否定,

not (a and b) 

应该完全工作,用 a 和 b 作为输入,还是我错过了什么?

【讨论】:

    【解决方案2】:

    口译:

    树 2 的 x 和 y 都与树 1 的 x 和 y 不同

    作为:

    树 2 的 x 和 y 与树 1 的 x 和 y 不同

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

    【讨论】:

      【解决方案3】:

      同样,你也可以使用~(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
      

      【讨论】:

        【解决方案4】:

        这将在字典中提供所有六个逻辑门功能(包括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
        

        【讨论】:

          猜你喜欢
          • 2010-09-30
          • 2023-03-31
          • 1970-01-01
          • 2014-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多