最小和最大树段

2024-04-26 05:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个段树,它的父节点应该包含其子节点的最小值和最大值节点。现在当我试图实现这一点时,我遇到了一个错误,即一个子函数可以返回一个整数,而另一个子函数可以返回一个列表,并且操作max或min函数将引发一个错误。怎么了为了克服这个问题?在

from math import log2,ceil
def segment(low,high,pos):

    if (low==high):
        segment_tree[pos]=arr[low]
        return

    mid=(high+low)//2

    segment(low,mid,2*pos+1)
    segment(mid+1,high,2*pos+2)

    segment_tree[pos]=[min(segment_tree[2*pos+1],segment_tree[2*pos+2]),max(segment_tree[2*pos+1],segment_tree[2*pos+2])]

length=5
arr=[1,2,3,4,5]
low=0
high=length-1
height=int(ceil(log2(length)))
pos=0 
size_of_segment_tree=2*int(pow(2,height))-1
segment_tree=[0]*size_of_segment_tree
segment(low,high,pos)

Tags: postree节点错误segmentminlog2length
2条回答

这将使用isinstance(object,list)工作

segment_tree[pos]=[min(min(segment_tree[2*pos+1]) if isinstance(segment_tree[2*pos+1],list) else segment_tree[2*pos+1],min(segment_tree[2*pos+2]) if isinstance(segment_tree[2*pos+2],list) else segment_tree[2*pos+2]),max(max(segment_tree[2*pos+1]) if isinstance(segment_tree[2*pos+1],list) else segment_tree[2*pos+1],max(segment_tree[2*pos+2]) if isinstance(segment_tree[2*pos+2],list) else segment_tree[2*pos+2])]

编辑:为清晰起见重新格式化:

^{pr2}$

如果我理解正确的话,你可以自己编写一个min/max函数:

def my_min(value):
    if isinstance(value, list):
        return min(value)
    else:
        return value

def my_max(value):
    if isinstance(value, list):
        return max(list)
    else:
        return value

相关问题 更多 >