2

I am trying to build a segment tree whose parent node should contain min and max values of its children nodes.Now when I am trying to implement this I am facing an error which is that one child can return an integer whereas other child can return a list and operating max or min function will raise an error.How to overcome this?

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)
rnso
  • 23,686
  • 25
  • 112
  • 234
Om Sharma
  • 335
  • 1
  • 11

2 Answers2

1

This will work using 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])]

Edit: reformatting for clarity:

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])
        ]
rnso
  • 23,686
  • 25
  • 112
  • 234
Demonking28
  • 749
  • 7
  • 21
0

You could write a min/max function yourself if I understood the problem right:

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
meow
  • 2,062
  • 2
  • 17
  • 27