Python 构建逻辑门

Python 构建逻辑门,python,python-2.7,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): ass

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

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              
消息文件名行位置
回溯
51
也不是18岁
断言错误:Nor的输入不是位类型
我不明白,如果我只向函数的输入发送
1
s,为什么它会引发我的断言。请注意:

if (a == 0 | a == 1):
由于Python的原因,评估为:

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

if (a == 0) | (a == 1):
但在我看来,这只是:

return a in {0, 1} 

更整洁。您不应该让
返回True
if
在同一行,您可以直接返回布尔值

为什么不直接
返回a==0或a==1
,或者
在{0,1}
中返回a?您不必对所有内容都使用位运算符!你应该在把它们粘在一起之前,单独尝试你的功能,以确保它们能正常工作;它使测试更容易。例如:
对于(0,1,True,False)中的位:打印位,isbit(位)
。惊讶?既然Python内置操作符没有做任何事情,为什么还要编写所有这些函数呢?我可能看到了
NAND
NOR
的用法,但是像你的
Not
函数这样的东西并没有真正添加任何东西。好吧,所有这些函数都已经存在于中。修复你代码中的标识我发现这个注释非常有用,谢谢。我还看到了您对for(0,1,true,false)所做的操作,它帮助我理解了我的错误,但我不确定我是否完全理解了您的解决方案。选择字典而不是列表或元组有什么原因吗?还有,当我在做某件事时,它会迭代整个对象项吗?至于其他问题,我正在尝试构建一个程序来解决一个基于逻辑门的复杂设计,对如何做(图形和树)有一点线索,但需要从一些东西开始。@maor“我不确定我是否完全理解您的解决方案”并不是一个真正的问题。你到底了解什么,又逃避什么?你也已经发现我有C++的经验,不是很高的水平,但我正在学习OOP。另外,你所写的东西都不是面向对象的,所以我不明白为什么会有问题。@maor你不能在注释中放换行符(如果你认为需要的话,它太长了!)
x-in-y
调用
y.\uu包含\uuuuuux)
;在这种情况下,
y
是一个
set
(基本上只是一个键
dict
),因此查找速度比
列表
元组
O(1)
vs
O(n)
)要快,因为它是基于散列的(即不会像在其他列表中那样“运行所有项”)。