我正在尝试构建一个段树,其父节点应该包含其子节点的最小值和最大值。现在当我尝试实现它时,我面临一个错误,即一个子节点可以返回整数而其他子节点可以返回一个列表并运行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)
答案 0 :(得分:1)
这将使用isinstance(对象,列表)
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])]
编辑:为了清晰起见重新格式化:
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])
]
答案 1 :(得分:0)
如果我理解问题,你可以自己写一个最小/最大功能:
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