Man in Black
Man in Black

Reputation: 109

Building logic gates

I am trying to build a program that will help to solve a complex logic gate scheme. In order to do so, I tried to build basic logic gates and ran a test on them:

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

the scripter returns :

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

I don't get it why it raises my assertion if I send to the function's inputs only 1s.

Upvotes: 4

Views: 1082

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122144

Note that:

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

is, due to Python's operator precedence, evaluated as:

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

(Python isn't C, you don't always need parentheses after if) which can clearly only be true when a == 1. Instead, if you're determined to use bitwise operators everywhere, you should have written:

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

To my mind, though, simply:

return a in {0, 1} 

is much neater. You shouldn't have the return True on the same line as the if, and you can return the Boolean directly.

Upvotes: 4

Related Questions