首页 > 解决方案 > 如何在代码中表示组合电路

问题描述

我正在编写一个 python 程序,它对组合电路执行一些操作,例如比较与其他电路的相等性、合并门、计数门、计数连接、查找扇出门,...

现在我用以下方式表示组合电路:(
我还添加了相等性测试)

class Circuit:
    def __init__(self):
        self.gates = {}  # key = the gates number, value = the gate

    def __eq__(self, other):
        if set(self.gates.keys()) != set(other.gates.keys()):
            return False
        for key in self.gates.keys():
            if self.gates[key] != other.gates[key]:
                return False
        return True


class Gate:
    def __init__(self, gate_type, number):
        self.gate_type = gate_type  # and, or, nand, nor, xor, xnor
        self.number = number
        self.incoming_gates = []
        self.outgoing_gates = []

    def __eq__(self, other):
        # i know this is not correct, but in my case correct enough
        return (
            self.gate_type == other.gate_type
            and self.number == other.number
            and len(self.incoming) == len(other.incoming)
            and len(self.outgoing) == len(other.outgoing)
        )

我在代码中的表示对我来说似乎很费力,所以我正在寻找一种更好的方法来做到这一点。我已经搜索了这方面的最佳实践,但没有找到任何东西。

标签: pythoncircuit

解决方案


您可以通过仅存储入站门引用来避免 Gate 类中的冗余,但这会使您的其余代码实现起来更加复杂。我相信冗余与易用性的权衡应该有利于易用性。

我不知道你是如何实现门之间的连接的,但是如果你在 self.incoming_gates / self.outgoing_gates 中保存对象引用,你可能只根据传入链接定义它们,并使用 self 自动更新源的输出门列表(可能在构造函数本身中)


推荐阅读