-1

I am to define a function called get_parent(a_list, index) which takes a binary min-heap represented by a Python list and an integer as parameters. The function should return the value of the parent of the element specified by the parameter index. The function should return None if the index is out of the valid range. I can assume that the parameter list is not empty.

This is the code I have so far:

def get_parent(a_list, index):
    if index in range(len(a_list)):
        parent = a_list[index // 2]
    
    else:
        parent = None
    return parent

This code seems to be working for all other cases. When the parameter index is 1 though, I think what is happening is 1//2 = 0 so its outputting 0? and since at index 0 we have 0, the result is 0. Now how do I stop this from happening?

>>>print(get_parent([0, 5, 7, 6, 13, 8, 22, 8, 19], 1))
None #expect
0 #got

>>>print(get_parent([0, 5, 7, 6, 13, 8, 22, 8, 19], 4))
7 #expect
7  #got

>>>print(get_parent([0, 5, 7, 6, 13, 8, 22, 8, 19], 9))
None  #expect
None   #got
  • *"Now how do I stop this from happening?"* - Why would you even want to? It's *correct*. You should expect `0` there, not `None`. – Kelly Bundy Feb 14 '22 at 10:11

1 Answers1

0

This should be an easy fix, try this:

def get_parent(a_list, index):
    if 1 < index < len(a_list):
        parent = a_list[index // 2]
        return parent
yowhatsup123
  • 287
  • 1
  • 11