构建逻辑门

2024-10-01 07:40:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个程序,将有助于解决一个复杂的逻辑门方案。为此,我尝试构建基本逻辑门,并对其进行了测试:

def isbit(a):
    if(a==0 | a==1) : return True
    return False
  / # creation Not,Nor,Nand,Or(|),And(&),Xor(^) even tho by using bitwise     operators that exsit in phyton.
def Nor(a,b):
    assert(isbit(a) & isbit(b)) ,"inputs to Nor are not Bit Type" # asserst     is equal to  raise - if - not
    return not(a|b)

def Or(a,b):
    assert(isbit(a) & isbit(b)) ,"inputs to or are not Bit Type" # asserst     is equal to  raise - if - not
    return (a|b)

def Xor(a,b):
    assert(isbit(a) & isbit(b)) ,"inputs to or are not Bit Type" # asserst     is equal to  raise - if - not
    return (a^b)

def And(a,b):
    assert(isbit(a) & isbit(b)) ,"inputs to or are not Bit Type" # asserst     is equal to  raise - if - not
   return (a&b)

def Nand(a,b):
    assert(isbit(a) & isbit(b)) ,"inputs to or are not Bit Type" # asserst is equal to  raise - if - not
   return not(And(a,b))

def Not(a):
   assert(isbit(a)) ,"inputs to or are not Bit Type" # asserst is equal to      raise - if not
    return not(a)


def main():
   pass

 if __name__ == '__main__':
    main()


x=1
y=1
print Xor(Nor(And(x,y),Nand(x,y)),Or(And(x,y),Nand(x,y)))

脚本编写器返回:

^{pr2}$

我不明白为什么如果我只发送给函数的输入1s,它会引发我的断言


Tags: toreturnifisdeftypebitnot
1条回答
网友
1楼 · 发布于 2024-10-01 07:40:58

请注意:

if (a == 0 | a == 1):

由于Python的operator precedence,计算结果为:

^{pr2}$

(Python不是C,你不需要总是在if后面加括号)这显然只有在a == 1时才是真的。相反,如果您决定在任何地方都使用按位运算符,则应该编写:

if (a == 0) | (a == 1):

不过,在我看来,很简单:

return a in {0, 1} 

更整洁。您不应该将return Trueif放在同一行,您可以直接返回布尔值。在

相关问题 更多 >