建立逻辑门

时间:2015-05-25 07:51:18

标签: python python-2.7

我正在尝试构建一个有助于解决复杂逻辑门方案的程序。为了做到这一点,我尝试构建基本的逻辑门并对它们进行测试:

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)))

脚本编写者返回:

Message File Name   Line    Position    
Traceback               
    <module>    <module1>   51      
    Nor <module1>   18      
AssertionError: inputs to Nor are not Bit Type              

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

1 个答案:

答案 0 :(得分:4)

请注意:

function A()
由于Python的operator precedence

被评估为:

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

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

a == 1

但在我看来,简单地说:

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

更整洁。你不应该在return a in {0, 1} 的同一行上有return True,你可以直接返回布尔值。