这是一个具有额外功能的堆节点;基于模2的“负载平衡”:
#! /usr/bin/env python
class Lifo:
def __init__(self):
# repr using tuple
self.lifo = ()
def push(self, data):
# pack data using tuple
self.lifo = (data, self.lifo)
def pop(self):
# unpack data using tuple
# raise ValueError when empty
data, self.lifo = self.lifo
return data
def __len__(self):
return len(self.lifo)
def __repr__(self):
return str(self.lifo)
class HeapNode:
def __init__(self, value, left=None, right=None):
self.data = value
self.left = left
self.right = right
def __repr__(self):
if self.left is None and self.right is None:
return '(%s)'%(self.data)
repr_left = '*' if self.left is None else repr(self.left)
repr_right = '*' if self.right is None else repr(self.right)
return '(%s L%s R%s)'%(self.data, repr_left, repr_right)
def add(self,data,count):
# do traversal with stack
lifo = Lifo()
lifo.push(self)
print 'push\'d self is %s, lifo is %s'%(self,lifo)
while len(lifo) > 0 :
# self's modified here
self = lifo.pop()
print 'popp\'d self is %s, lifo is %s'%(self,lifo)
if count % 2 == 0 :
if self.right is None:
self.right = HeapNode(data)
else:
lifo.push(self.right)
else:
if self.left is None:
self.left = HeapNode(data)
else:
lifo.push(self.left)
print 'returning self is %s'%(self,)
return self
if __name__ == '__main__':
heap = HeapNode(11)
heap.add(7,0).add(4,1).add(10,2)
输出:
push'd self is (11), lifo is ((11), ())
popp'd self is (11), lifo is ()
returning self is (11 L* R(7))
heap [(11 L* R(7))]
push'd self is (11 L* R(7)), lifo is ((11 L* R(7)), ())
popp'd self is (11 L* R(7)), lifo is ()
returning self is (11 L(4) R(7))
heap [(11 L(4) R(7))]
push'd self is (11 L(4) R(7)), lifo is ((11 L(4) R(7)), ())
popp'd self is (11 L(4) R(7)), lifo is ()
popp'd self is (7), lifo is ()
returning self is (7 L* R(10))
heap [(11 L(4) R(7 L* R(10)))]
上述情况是如何发生的,即self
(在 add 函数内)是(7 L* R(10)
但引用了堆(11 L(4) R(7 L* R(10)))
?
我明白,如果它是主要的:heap = heap.add_stack(10,2)
那么,返回值是堆。
但我不明白的是什么是添加元素11 L(4)
,(7 L* R(10))
是不是一些引用和值传递导致了这个?
有人可以解释清楚吗?