【发布时间】:2020-05-12 11:15:56
【问题描述】:
因此,作为我编程研究的一部分,我正在制作一个不相交的集合数据结构。但是,一种方法需要获取两个节点,如果它们不是相同的节点,则加入节点。这应该通过将一个节点的父属性设置为另一个节点来完成。但是,在使用调试器单步执行该方法后,父值永远不会改变。部分代码供参考:
class Node:
# a bare bones node class representing an entry in the disjoint set
# track the ids as a static variable
id = 0
def __init__(self):
self.id = Node.id
Node.id += 1
self.parent = None
self.rank = 0
还有问题代码本身,不相交集类中的一个方法:
def union(self, u, v):
# the union operation is used to join two components into one
# this implementation uses the component's ranks to optimize the union operation
# in this varient, the component with the lesser rank is attached to the root with the greater rank
# the find method searches for a particular node, and returns a Node object
# (an instance of the above class)
u_root = self.find(u)
v_root = self.find(v)
# if u and v's root are the same, they are in the same component
# therefore, end the operation because they are already merged
if u_root.id == v_root.id:
return
# to simplify coding, we force the u root to always be the root of lower rank
if u_root.rank > v_root.rank:
u_root, v_root = v_root, u_root
# merge u root into v root
u_root.parent = v_root
# the offending bit of code that isn't working as intended
# if the two roots share the same rank, you can't just add one onto the other
if v_root.rank == u_root.rank:
v_root.rank += 1
我怀疑我在假设变量赋值在 Python 中是如何工作的,尤其是在涉及 Python 对象时。我认为分配给 Python 对象的变量和属性将其视为引用,并且任何引用同一对象的变量都可以对其进行编辑。但是,我肯定陷入了僵局,需要一些方向。
【问题讨论】:
-
当您在调试器中单步执行时 - 您是说
u_root.parent = v_root行正在执行,但 u_root.parent 在该行之后仍然为 None 。u_root.parent是属性而不是属性(也许?) -
听起来您希望
+=操作就地修改int值,但int值是不可变的。确实x和y可以引用同一个int对象,但x += 1实际上是x = x.__iadd__(1),并且由于int.__iadd__甚至没有定义,它进一步简化为x = x.__add__(1),即只需创建一个新int值并将其分配给x,让y引用原始值。 -
@TonySuffolk66 因此,当我使用调试器单步执行时,在调用
u_root.parent = v_root之后,u_root.parent仍被分配了一个值None。我知道 Python 属性是一个属性,其中 getter 和 setter 用于控制对值的访问,但根对象是裸骨 Node 类的实例,因此没有使用 getter/setter 的值(除非我误解了 Python 中的属性是什么)。还是说我应该使用 getter/setter 来修改这个值? -
你不需要使用getter/setter——我只是想知道你是否在使用它们,因为它们可能会阻止你设置一些值;是
v_root绝对不是None吗? -
@TonySuffolk66
v_root的值肯定不是None
标签: python python-3.x oop