我正在尝试建立一个程序,将有助于解决一个复杂的逻辑门方案。为此,我尝试构建基本逻辑门,并对其进行了测试:
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}$我不明白为什么如果我只发送给函数的输入1
s,它会引发我的断言
请注意:
由于Python的operator precedence,计算结果为:
^{pr2}$(Python不是C,你不需要总是在
if
后面加括号)这显然只有在a == 1
时才是真的。相反,如果您决定在任何地方都使用按位运算符,则应该编写:不过,在我看来,很简单:
更整洁。您不应该将
return True
与if
放在同一行,您可以直接返回布尔值。在相关问题 更多 >
编程相关推荐