Last active
May 21, 2017 06:42
-
-
Save ttowncompiled/9f266036f54b82c0a572b2bbef5275e2 to your computer and use it in GitHub Desktop.
A MinHeap to use for HackerRank problems.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# Python 3 - MinHeap | |
# H = [] | |
### | |
def size(H): | |
return len(H) | |
def is_empty(H): | |
return len(H) == 0 | |
def peek(H): | |
return H[0] if len(H) > 0 else None | |
def put(H, x): | |
H.append(x) | |
i = len(H)-1 | |
P_i = (i-1) // 2 if i % 2 == 1 else (i-2) // 2 | |
while P_i > -1 and H[i] < H[P_i]: | |
H_Pi = H[P_i] | |
H[P_i] = H[i] | |
H[i] = H_Pi | |
i = P_i | |
P_i = (i-1) // 2 if i % 2 else (i-2) // 2 | |
def remove(H, i): | |
if len(H) == 0 or i < 0 or i >= len(H): | |
return None | |
if i == len(H) - 1: | |
return H.pop() | |
H_i = H[i] | |
H[i] = H.pop() | |
L_i, R_i = 2*i+1, 2*i+2 | |
while (L_i < len(H) and H[L_i] < H[i]) or (R_i < len(H) and H[R_i] < H[i]): | |
if L_i < len(H) and H[L_i] < H[i] and (R_i >= len(H) or H[L_i] < H[R_i]): | |
H_Li = H[L_i] | |
H[L_i] = H[i] | |
H[i] = H_Li | |
i = L_i | |
else: | |
H_Ri = H[R_i] | |
H[R_i] = H[i] | |
H[i] = H_Ri | |
i = R_i | |
L_i, R_i = 2*i+1, 2*i+2 | |
return H_i | |
def remove_item(H, x): | |
return remove(H, H.index(x)) | |
def take(H): | |
return remove(H, 0) | |
# The End |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment