📅  最后修改于: 2023-12-03 15:12:38.077000             🧑  作者: Mango
这是一道来自 GATE CS Mock 2018 的编程题,要求实现一个门类 Gate
和一个分支门类 OrGate
继承 Gate
。我们需要实现以下功能:
Gate
类需要实现一个 performGateLogic()
方法;OrGate
类需要继承 Gate
类,重载 performGateLogic()
方法并实现与门的逻辑;Gate
类需要包含前一个门(pinA
)和后一个门(pinB
)的引用,如果没有前一个门时,pinA
可设置为 None
,如果没有后一个门,pinB
可设置为 None
;Gate
类需要包含一个 label
属性,用于在多门电路中标识门的位置。以下是代码骨架,您需要对其进行完善:
class LogicGate:
def __init__(self, n):
self.label = n
self.output = None
def getLabel(self):
return self.label
def getOutput(self):
self.output = self.performGateLogic()
return self.output
def performGateLogic(self):
pass
class BinaryGate(LogicGate):
def __init__(self, n):
LogicGate.__init__(self, n)
self.pinA = None
self.pinB = None
def getPinA(self):
if self.pinA == None:
return int(input("Enter Pin A input for gate " + self.getLabel()+"-->"))
else:
return self.pinA.getFrom().getOutput()
def getPinB(self):
if self.pinB == None:
return int(input("Enter Pin B input for gate " + self.getLabel()+"-->"))
else:
return self.pinB.getFrom().getOutput()
def setNextPin(self, source):
if self.pinA == None:
self.pinA = source
else:
if self.pinB == None:
self.pinB = source
else:
raise RuntimeError("Error: NO EMPTY PINS")
class AndGate(BinaryGate):
def __init__(self, n):
BinaryGate.__init__(self, n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a==1 and b==1:
return 1
else:
return 0
class OrGate(BinaryGate):
def __init__(self, n):
BinaryGate.__init__(self, n)
def performGateLogic(self):
# 在这里实现或门的逻辑
pass
class UnaryGate(LogicGate):
def __init__(self, n):
LogicGate.__init__(self, n)
self.pin = None
def getPin(self):
if self.pin == None:
return int(input("Enter Pin input for gate " + self.getLabel()+"-->"))
else:
return self.pin.getFrom().getOutput()
def setNextPin(self, source):
if self.pin == None:
self.pin = source
else:
raise RuntimeError("Error: NO EMPTY PINS")
class NotGate(UnaryGate):
def __init__(self, n):
UnaryGate.__init__(self, n)
def performGateLogic(self):
if self.getPin():
return 0
else:
return 1
class Connector:
def __init__(self, fgate, tgate):
self.fromgate = fgate
self.togate = tgate
tgate.setNextPin(self)
def getFrom(self):
return self.fromgate
def getTo(self):
return self.togate
希望您可以成功完成这道编程题!