Advertisement
Tyler_Elric

pydigi.py

Aug 23rd, 2016
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1.  
  2. class Node(object):
  3.     AND = '&'
  4.     NAND = '!&'
  5.     OR = '|'
  6.     NOR = '!OR'
  7.     XOR = '^'
  8.     XNOR = '!^'
  9.     NOT = '!'
  10.     value = False
  11.     def  __init__(self,op):
  12.         self.op = op
  13.         self.connections = set()
  14.     def __call__(self):
  15.         vals = list(map((lambda x:x.value),self.connections))
  16.         op = self.op[:]
  17.         if len(op) < 1: return
  18.         invert = op[0]=='!'
  19.         if invert:
  20.             op = op[1:]
  21.         def odd(l):
  22.             i = 0
  23.             for v in l:
  24.                 i += 1 if v else -1
  25.             return i==0
  26.         v = {
  27.             '&': all,
  28.             '|': any,
  29.             '^': odd,
  30.             '': next
  31.         }[op](vals)
  32.         self.value = not v if invert else v
  33.     @classmethod
  34.     def build_circuit(cls,circuit):
  35.         c = dict(map((lambda x:(x[0],Node(x[1].get("op","")))),circuit.items()))
  36.         for n in circuit.keys():
  37.             for cnxn in circuit[n].get("connections",[]):
  38.                 c[n].connections.add(c[cnxn])
  39.         return c
  40.  
  41. if __name__=="__main__":
  42.     circuit = Node.build_circuit({
  43.         "n":{
  44.             "op":Node.NAND,
  45.             "connections":[
  46.             "a",
  47.             "b"
  48.         ]
  49.     },
  50.         "a":{},
  51.         "b":{}
  52.     })
  53.  
  54.     circuit["a"].value = False
  55.     circuit["b"].value = False
  56.     circuit["n"]()
  57.     print(circuit["n"].value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement