Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node(object):
- AND = '&'
- NAND = '!&'
- OR = '|'
- NOR = '!OR'
- XOR = '^'
- XNOR = '!^'
- NOT = '!'
- value = False
- def __init__(self,op):
- self.op = op
- self.connections = set()
- def __call__(self):
- vals = list(map((lambda x:x.value),self.connections))
- op = self.op[:]
- if len(op) < 1: return
- invert = op[0]=='!'
- if invert:
- op = op[1:]
- def odd(l):
- i = 0
- for v in l:
- i += 1 if v else -1
- return i==0
- v = {
- '&': all,
- '|': any,
- '^': odd,
- '': next
- }[op](vals)
- self.value = not v if invert else v
- @classmethod
- def build_circuit(cls,circuit):
- c = dict(map((lambda x:(x[0],Node(x[1].get("op","")))),circuit.items()))
- for n in circuit.keys():
- for cnxn in circuit[n].get("connections",[]):
- c[n].connections.add(c[cnxn])
- return c
- if __name__=="__main__":
- circuit = Node.build_circuit({
- "n":{
- "op":Node.NAND,
- "connections":[
- "a",
- "b"
- ]
- },
- "a":{},
- "b":{}
- })
- circuit["a"].value = False
- circuit["b"].value = False
- circuit["n"]()
- print(circuit["n"].value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement