为Bradley N. Miller与David L. Ranum的《Python数据结构与算法分析(第2版)》(人民邮电出版社出版出版,封面如下图1+)一书 整理复现书中对于初学者来说不太容易理解的代码。代码已测试通过,方便各位初学者道友参考对照学习。
图1 封面
第一章 导论
1.4 Python基础 逻辑门电路
文件名:LogicGate.py
1 class LogicGate: 2 """ 3 超类 4 """ 5 6 def __init__(self,n): 7 self.label = n 8 self.output = None 9 10 def getLabel(self): 11 return self.label 12 13 def getOutput(self): 14 self.output = self.performGateLogic() 15 return self.output 16 17 class BinaryGate(LogicGate): 18 """ 19 双输入门 20 """ 21 22 def __init__(self,n): 23 super().__init__(n) 24 25 self.pinA = None 26 self.pinB = None 27 28 def getPinA(self): 29 if self.pinA == None: 30 return int(input("Enter Pin A input for gate " + \ 31 self.getLabel() + "-->")) 32 else: 33 return self.pinA.getFrom().getOutput() 34 35 def getPinB(self): 36 if self.pinB == None: 37 return int(input("Enter Pin B input for gate " + \ 38 self.getLabel() + "-->")) 39 else: 40 return self.pinB.getFrom().getOutput() 41 42 43 44 def setNextPin(self,source): 45 if self.pinA == None: 46 self.pinA = source 47 elif self.pinB == None: 48 self.pinB = source 49 else: 50 raise RuntimeError("Error: NO EMPTY PINS") 51 52 class UnaryGate(LogicGate): 53 """ 54 但输入门 55 """ 56 57 def __init__(self,n): 58 super().__init__(n) 59 60 self.Pin = None 61 62 def getPin(self): 63 if self.Pin == None: 64 return int(input("Enter Pin input for gate" + \ 65 self.getLabel()+"-->")) 66 else: 67 return self.Pin.getFrom().getOutput() 68 69 def setNextPin(self,source): 70 if self.Pin == None: 71 self.Pin= source 72 else: 73 raise RuntimeError("Error: NO EMPTY PINS") 74 75 class AndGate(BinaryGate): 76 77 def __init__(self,n): 78 super().__init__(n) 79 80 def performGateLogic(self): 81 82 a = self.getPinA() 83 b = self.getPinB() 84 if a == 0 or b == 0 : 85 return 0 86 else: 87 return 1 88 class OrGate(BinaryGate): 89 def __init__(self,n): 90 super().__init__(n) 91 92 self.PinA = None 93 self.PinB = None 94 95 def performGateLogic(self): 96 97 a = self.getPinA() 98 b = self.getPinB() 99 if a == 1 or b == 1 : 100 return 1 101 else : 102 return 0 103 104 class NotGate(UnaryGate): 105 106 def __init__(self,n): 107 super().__init__(n) 108 109 def performGateLogic(self): 110 a = self.getPin() 111 return 0 if a else 1 # return int(not a) 112 113 114 class Connector: 115 116 def __init__(self,fgate,tgate): 117 self.fromgate = fgate 118 self.togate = tgate 119 120 tgate.setNextPin(self) 121 122 def getFrom(self): 123 return self.fromgate 124 125 def getTo(self): 126 return self.togate 127 128 129 130 131
测试代码如下:
文件名 test.py
import LogicGateg1 = LogicGate.AndGate('G1') # print(g1.getOutput()) g2 = LogicGate.AndGate("G2") # print(g2.getOutput()) g3 = LogicGate.OrGate("G3") # print(g3.getOutput()) g4 = LogicGate.NotGate("G4") # print(g4.getOutput()) c1 = LogicGate.Connector(g1, g3) c2 = LogicGate.Connector(g2, g3) c3 = LogicGate.Connector(g3, g4)print(g4.getOutput())