【问题标题】:How to represent combinational circuits in code如何在代码中表示组合电路
【发布时间】:2021-12-08 14:24:17
【问题描述】:

我正在编写一个 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)
        )

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

【问题讨论】:

  • dataclasses(标准库)或attrs会在一定程度上帮助你。
  • @AKX 我明白为什么dataclassesattrs 都有助于编写更少、更精确的代码,但它对表示有何帮助?
  • 你的表现很好。 dataclasses 将有助于样板文件,但您表示数据的方式没有任何问题。你已经很好地掌握了如何使用类,在我看来是这样的

标签: python circuit


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您希望实现一个有向图,其中某些数据存储在顶点中。 Wikipedia has a discussion of various ways to represent a graphhere's a stackoverflow 谈论更普遍的问题。

    对于快速修改图的拓扑结构以及进行(合并门等)类似您的邻接列表通常很有用。

    一般来说,我认为对架构的测试是在您真正开始实施它时进行——我猜想一旦您开始使用它,您就会很快熟悉您的设计的好处和坏处,并且能够根据需要调整或构建辅助函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2021-12-28
      • 2013-04-19
      • 1970-01-01
      相关资源
      最近更新 更多