-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.py
106 lines (82 loc) · 2.48 KB
/
Heap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
def digit_number(number):
counter = 0
while number>0:
number = number//10
counter+=1
return counter
class Heap:
def __init__(self):
self.heap = []
def swap(self,a,b):
temp = self.heap[a]
self.heap[a] = self.heap[b]
self.heap[b] = temp
def insert(self,data):
self.heap.append(data)
self.swapup(len(self.heap)-1)
def swapup(self,index):
while index!=0:
oldindex = int((index-1)/2)
if self.heap[index] < self.heap[oldindex]:
self.swap(oldindex,index)
index = oldindex
else:
break
def swapdown(self,index):
leftindex = (index*2)+1
rightindex = (index*2)+2
if leftindex < len(self.heap):
min = leftindex
if rightindex < len(self.heap):
if self.heap[rightindex]<self.heap[leftindex]:
min = rightindex
if self.heap[min]<self.heap[index]:
self.swap(min,index)
self.swapdown(min)
else:
return
else:
return
def pop(self):
if len(self.heap)>0:
head = self.heap[0]
popped = self.heap.pop()
if len(self.heap)>1:
self.heap[0] = popped
self.swapdown(0)
return head
else:
return None
def print(self):
number = 1;
counter = 0
done = False
distance = 120
initialdistance = 60
while done == False:
print(' '*initialdistance, end = '')
for i in range (0,number):
if counter < len(self.heap):
print(self.heap[counter],end = ' '*(distance-(digit_number(self.heap[counter]) - 1)))
counter +=1
else:
done = True
break
digitcounter = 0
distance = int(distance/2)
initialdistance = initialdistance-int(distance/2)
print()
number = number *2
hep = Heap()
while True:
print('Enter data: ', end = '')
a = input()
if a.isalpha():
if a == 'p':
hep.print()
else:
print('Popped: ', hep.pop())
hep.print()
else:
hep.insert(int(a))
hep.print()