In: Computer Science
Write a function child_indices(parent, branch_factor) that returns a list containing the list of indices where the children of the node at index parent will be stored for a heap list with the given branch_factor (ie, a branch_factor-heap). Python language
Notes:
Test | Result |
---|---|
print(child_indices(1,2)) |
[2, 3] |
print(child_indices(2,2)) |
[4, 5] |
print(child_indices(1,3)) |
[2, 3, 4] |
Hope this will help you, if you have any doubt please let me know.
Please let me know if you want any modification in the program (I have used a for loop in it)
Notes:-There are no restriction is provided in the statement, hence I have made this way, over here we have to just compute child indices. (We are not caring about the value stored at those indices)
We have also given the values in the heap list start at index 1. That is the root of the heap is at index 1 in the heap list.
Code is well commented also output of screenshot is attached.
Please feel free to ask me anything at anytime.
Also tested with additional test cases please see the screenshot
------------------Code-----------------
def child_indices(parent, branch_factor):
indices=[] #list that returns a branch indices
if(branch_factor>=2): #checking if branch_factor is greater than
1
# for loop iterate till branch factor (means i have a value
starting from 0 to branch factor-1)
for i in range(branch_factor):
# then calculting indices using following formula
#lets take a parent=2 and branch_factor 3
# first root node is 1 whose childer is at index 2,3,4
#now parent=2 whose child are at index 5,6,7
#first child is obtained
=3(branch_factor)*2(parent)-((branch_factor)3-2)+(i=0 for first
iteration)
#firstchild=6-1+0(i=0)=5
#seconchild=6-1+1 (i=1)=6
#same for child three,
#works for all cases
k=branch_factor*parent-(branch_factor-2)+i # calculating child
indices
indices.append(k)# adding indices into list
#useless case
else:
k=branch_factor*parent+1 # if branch_factor is 1 its child index is
incremented by 1
indices.append(k) # adding indices into list
return indices # returning the list
print(child_indices(1,2))
print(child_indices(2,2))
print(child_indices(1,3))
-------------------------------------------output----------