class HeapArray:
def __init__(self):
self._data = [] # indefinite size list; insert cannot fail
self._size = 0
def __str__(self):
return ' '.join([str(i) for i in self._data])
def is_empty(self):
return self._size == 0
def insert(self,e):
#self._data.insert(self._size,e)
self._data.append(e)
index = self._size
while index > 0 and self._data[index] < self._data[(index-1)//2]:
# Send value up the tree
temp = self._data[index]
self._data[index] = self._data[(index-1)//2]
self._data[(index-1)//2] = temp
index = (index-1)//2
self._size = self._size + 1
return True
def delete_min(self):
if self.is_empty():
return None
elif self._size == 1:
return self._data.pop(0)
else:
smallest = self._data[0]
self._data[0] = self._data.pop(self._size-1)
self._size = self._size - 1
index = 0
while 2*index+1 < self._size: # this condition means that there is at least one child
# check if there is a second child
if 2*index+2 < self._size: # 2 children
if self._data[2*index+1] < self._data[2*index+2]: # left child smaller than right child
if self._data[index] > self._data[2*index+1]:
temp = self._data[index]
self._data[index] = self._data[2*index+1]
self._data[2*index+1] = temp
index = 2*index+1
else: # right child is smaller than left child
if self._data[index] > self._data[2*index+2]:
temp = self._data[index]
self._data[index] = self._data[2*index+2]
self._data[2*index+2] = temp
index = 2*index+2
else: #one child
if self._data[index] > self._data[2*index+1]:
temp = self._data[index]
self._data[index] = self._data[2*index+1]
self._data[2*index+1] = temp
index = 2*index+1
return smallest
# CASE ANALYSIS
pq1 = HeapArray()
pq1.insert(8)
pq1.insert(14)
pq1.insert(2)
pq1.insert(10)
pq1.insert(26)
pq1.insert(3)
pq1.insert(1)
sm = pq1.delete_min()
print(pq1)
print(sm)
result = ""
for x in ["1","2","3","4"]:
result = result + x + ","
result = result[0:-1]
print(result)
print(','.join([str(i) for i in [1,2,3,4]]))
s = [2,5,7]
s.append(99)
print(s)
## SWAPPING values of variables
x = 5
y = 7
temp = y
y = x
x = temp
print(x)
print(y)