Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binary Heap get_parent() function in Python not working as expected

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>>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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading