python中的简单代码导致意外行为

时间:2013-04-21 19:29:16

标签: python algorithm runtime interval-tree segment-tree

我正在尝试在python中实现一个段树类。段树允许以对数时间(more about segment trees)查询范围。在我的实现中,我保留了必要的信息,以便能够回答(i, j)范围内元素的总和。下面是我的代码。由于我是python的新手,我仍然在每行的末尾使用分号(继承自C ++)。

class Node :
    val = 0;
    def __init__( self, _val ) :
        self.val = _val;

class ST :
    st = [];

    def __init__( self, N ) :
        self.st = [ Node( 0 ) ] * N * 4;

    def build( self, nd, lo, hi, a ) :
        print "build( self, {0}, {1}, {2}, {3})".format( nd, lo, hi, a );

        if lo == hi :
            print "setting self.st[{0}] to {1}".format( nd, a[ lo ] );
            self.st[ nd ].val = a[ lo ];
            print "done! now self.st[", nd, "] is ", self.st[ nd ].val;
        else :
            print "else statement for nd = {0}".format( nd );
            self.build( nd*2+1, lo, int( ( lo+hi )/2 ), a );
            self.build( nd*2+2, int( ( lo+hi )/2+1 ), hi, a );

            self.st[ nd ].val = self.st[ nd*2+1 ].val + self.st[ nd*2+2 ].val;
            print "self.st[{0}] is set to {1}".format( nd, self.st[ nd ].val );

    def echo( self ) :
        for i in self.st :
            print i.val;

def main( ) :
    tree = ST( 5 );
    a = [ 2, 3, 4, 5, 6 ];
    tree.build( 0, 0, 4, a );
    tree.echo( );

main( );

构建函数应该从输入数组a构建分段树。当我运行程序时,我得到以下输出:

build( self, 0, 0, 4, [2, 3, 4, 5, 6])
else statement for nd = 0
build( self, 1, 0, 2, [2, 3, 4, 5, 6])
else statement for nd = 1
build( self, 3, 0, 1, [2, 3, 4, 5, 6])
else statement for nd = 3
build( self, 7, 0, 0, [2, 3, 4, 5, 6])
setting self.st[7] to 2
done! now self.st[ 7 ] is  2
build( self, 8, 1, 1, [2, 3, 4, 5, 6])
setting self.st[8] to 3
done! now self.st[ 8 ] is  3
self.st[3] is set to 6
build( self, 4, 2, 2, [2, 3, 4, 5, 6])
setting self.st[4] to 4
done! now self.st[ 4 ] is  4
self.st[1] is set to 8
build( self, 2, 3, 4, [2, 3, 4, 5, 6])
else statement for nd = 2
build( self, 5, 3, 3, [2, 3, 4, 5, 6])
setting self.st[5] to 5
done! now self.st[ 5 ] is  5
build( self, 6, 4, 4, [2, 3, 4, 5, 6])
setting self.st[6] to 6
done! now self.st[ 6 ] is  6
self.st[2] is set to 12
self.st[0] is set to 24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24

24函数退出后,我无法理解为什么序列的所有值都是build。调试信息在build函数运行时显示许多其他值,但在退出后,所有值神奇地变为24。为什么会这样?提前谢谢。

1 个答案:

答案 0 :(得分:3)

这会创建一个N*4元素列表:

self.st = [ Node( 0 ) ] * N * 4;

尽管如此,所有这些元素都是Node

例如,这会创建N*4个不同的Node s:

self.st = [Node(0) for i in range(N * 4)]