Skip to content

Commit d7571c7

Browse files
committed
Refactoring
1 parent 998a67e commit d7571c7

10 files changed

+163
-56
lines changed

Array/maxAndMinProductSubArray.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,4 @@ def max_and_min_product_subarray(arr):
3131
if __name__ == "__main__":
3232
arr = [1, 0, -4, -2, 2, 3, -2]
3333
max_n_min = max_and_min_product_subarray(arr)
34-
print "Product of max-product-sub-array is {} & product of min-product-sub-array is {}".format(*max_n_min)
34+
print("Product of max-product-sub-array is {} & product of min-product-sub-array is {}".format(*max_n_min))

Array/maximizeProfit.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ def maximize_profit(prices):
6868
currency = "INR"
6969
prices = [2, 11, 10, 6, 9, 7, 16, 8, 3, 4, 14, 1, 10, 2]
7070
res = maximize_profit(prices)
71-
print """Maximum profit is {max_profit},
71+
print("""Maximum profit is {max_profit},
7272
Buy at price {currency} {buy_price} at index/time {buy_index}.
7373
Sell at price {currency} {sell_price} at index/time {sell_index}
7474
""".format(max_profit=res['max_profit'], currency=currency,
7575
buy_price=res['buy']['price'], buy_index=res['buy']['index'],
76-
sell_price=res['sell']['price'], sell_index=res['sell']['index'])
76+
sell_price=res['sell']['price'], sell_index=res['sell']['index']))

Array/stockSpanProblem.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,5 @@ def stock_span(prices):
2424
if __name__ == '__main__':
2525
prices = [10, 4, 5, 90, 120, 80]
2626
spans = stock_span(prices)
27-
print "Prices:", prices
28-
print "Spans:", spans
27+
print("Prices:", prices)
28+
print("Spans:", spans)

Heap/BinaryHeap/Heap.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,13 @@ def is_empty(self):
5757
return self.heap_size <= 0
5858

5959
def print_heap(self):
60-
for idx in xrange(0, self.heap_size):
60+
for idx in range(0, self.heap_size):
6161
l_idx = Heap.left(idx)
6262
r_idx = Heap.right(idx)
6363

6464
curr_elt = self.get(idx)
6565
l_elt = self.get(l_idx)
6666
r_elt = self.get(r_idx)
6767

68-
print "{current} : left -> {left} | right -> {right}".format(current=curr_elt,
69-
left=l_elt, right=r_elt)
68+
print("{current} : left -> {left} | right -> {right}".format(current=curr_elt,
69+
left=l_elt, right=r_elt))

Heap/BinaryHeap/maxHeap.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from Array import swap
2-
from Heap import Heap
2+
from Heap.BinaryHeap import Heap
33
from copy import deepcopy
44

55
class MaxHeap(Heap):
@@ -49,20 +49,20 @@ def build_heap(self, harr):
4949
:return:
5050
"""
5151
if len(harr) > self.capacity:
52-
print '''Can't build heap as the array contains {} elements,
53-
which is more than specified capacity({}) of heap'''.format(len(harr), self.capacity)
52+
print('''Can't build heap as the array contains {} elements,
53+
which is more than specified capacity({}) of heap'''.format(len(harr), self.capacity))
5454

5555
self.harr = harr
5656
self.heap_size = len(harr)
57-
half = self.heap_size / 2
57+
half = int(self.heap_size / 2)
5858

59-
for idx in xrange(half, -1, -1): # for idx=half; idx<=0; idx++
59+
for idx in range(half, -1, -1): # for idx=half; idx<=0; idx++
6060
self.max_heapify(idx)
6161

6262
# Time Complexity: O(log(n))
6363
def insert(self, elt):
6464
if self.is_full():
65-
print "Heap is full, can't insert key"
65+
print("Heap is full, can't insert key")
6666
return False
6767

6868
# First insert the new key at the end.
@@ -83,14 +83,14 @@ def insert(self, elt):
8383
# Time Complexity: O(1)
8484
def get_max(self):
8585
if self.is_empty():
86-
print "Heap is empty"
86+
print("Heap is empty")
8787
return False
8888
return deepcopy(self.harr[0])
8989

9090
# Time Complexity: O(log(n))
9191
def delete_max(self):
9292
if self.is_empty():
93-
print "Heap is empty"
93+
print("Heap is empty")
9494
return False
9595

9696
root = self.harr[0]
@@ -113,13 +113,13 @@ def delete(self, idx):
113113
mh = MaxHeap(12)
114114
mh.build_heap(harr)
115115

116-
print "Array {} is converted to Max-Heap {}".format(harr_copy, harr)
116+
print("Array {} is converted to Max-Heap {}".format(harr_copy, harr))
117117

118118
elt = 1
119119
mh.insert(elt)
120-
print "Inserted {}:".format(elt), harr
120+
print("Inserted {}:".format(elt), harr)
121121

122122
d_elt = mh.delete_max()
123-
print "Deleted maximum element(root)=>{}:".format(d_elt), harr
123+
print("Deleted maximum element(root)=>{}:".format(d_elt), harr)
124124

125125
#mh.print_heap()

Heap/BinaryHeap/minHeap.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from Array import swap
2-
from Heap import Heap
2+
from Heap.BinaryHeap import Heap
33
from copy import deepcopy
44

55
class MinHeap(Heap):
@@ -10,7 +10,7 @@ def min_heapify(self, index):
1010
Algorithm: We move downwards(bottom) in the heap in each step until heap is in it's correct form.
1111
1212
Min-Heapify (A, i):
13-
left = 2*i // = means "assignment"
13+
left = 2*i # `=` means `assignment`
1414
right = 2*i + 1
1515
smallest = i
1616
@@ -44,28 +44,28 @@ def min_heapify(self, index):
4444
def build_heap(self, harr):
4545
"""
4646
Build-Min-Heap (A):
47-
for i=floor(length[A]/2); i<=0; i--:
47+
for i=floor(length[A]/2); i>=0; i--:
4848
Min-Heapify(A, i)
4949
:param harr:
5050
:return:
5151
"""
5252

5353
if len(harr) > self.capacity:
54-
print '''Can't build heap as the array contains {} elements,
55-
which is more than specified capacity({}) of heap'''.format(len(harr), self.capacity)
54+
print('''Can't build heap as the array contains {} elements,
55+
which is more than specified capacity({}) of heap'''.format(len(harr), self.capacity))
5656

5757
self.harr = harr
5858
self.heap_size = len(harr)
59-
half = self.heap_size/2
59+
half = int(self.heap_size/2)
6060

61-
for idx in xrange(half, -1, -1): # for idx=half; idx<=0; idx++
61+
for idx in range(half, -1, -1): # for idx=half; idx>=0; idx--
6262
self.min_heapify(idx)
6363
return deepcopy(self.harr)
6464

6565
# Time Complexity: O(log(n))
6666
def insert(self, elt):
6767
if self.is_full():
68-
print "Heap is full, can't insert key"
68+
print("Heap is full, can't insert key")
6969
return False
7070

7171
# First insert the new key at the end.
@@ -86,14 +86,14 @@ def insert(self, elt):
8686
# Time Complexity: O(1)
8787
def get_min(self):
8888
if self.is_empty():
89-
print "Heap is empty"
89+
print ("Heap is empty")
9090
return False
9191
return deepcopy(self.harr[0])
9292

9393
# Time Complexity: O(log(n))
9494
def delete_min(self):
9595
if self.is_empty():
96-
print "Heap is empty"
96+
print ("Heap is empty")
9797
return False
9898

9999
root = self.harr[0]
@@ -116,13 +116,13 @@ def delete(self, idx):
116116
mh = MinHeap(12)
117117
mh.build_heap(harr)
118118

119-
print "Array {} is converted to Min-Heap {}".format(harr_copy, harr)
119+
print("Array {} is converted to Min-Heap {}".format(harr_copy, harr))
120120

121121
elt = 1
122122
mh.insert(elt)
123-
print "Inserted {}:".format(elt), harr
123+
print("Inserted {}:".format(elt), harr)
124124

125125
d_elt = mh.delete_min()
126-
print "Deleted minimum element(root)=>{}:".format(d_elt), harr
126+
print("Deleted minimum element(root)=>{}:".format(d_elt), harr)
127127

128128
#mh.print_heap()

Queues/PriorityQueue/pq.py

+17-18
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from Heap.BinaryHeap.maxHeap import MaxHeap
22
from copy import deepcopy
33

4-
54
class PriorityQueue(object):
65
def __init__(self, pq_capacity=10):
76
self._pq_capacity_ = pq_capacity
@@ -12,7 +11,7 @@ def __init__(self, pq_capacity=10):
1211
def insert(self, item, priority):
1312
res = False
1413
if self.is_full():
15-
print "Priority queue is full, please delete older items in order to insert newer ones."
14+
print("Priority queue is full, please delete older items in order to insert newer ones.")
1615
return res
1716
e = Entry(item, priority)
1817
res = self._pq_heap_.insert(e)
@@ -24,7 +23,7 @@ def insert(self, item, priority):
2423
def delete_item_with_highest_priority(self):
2524
res = False
2625
if self.is_empty():
27-
print "Priority queue is empty"
26+
print("Priority queue is empty")
2827
return res
2928
res = self._pq_heap_.delete_max()
3029
if isinstance(res, bool) and res == False:
@@ -36,7 +35,7 @@ def delete_item_with_highest_priority(self):
3635
# Time Complexity : O(1)
3736
def get_item_with_highest_priority(self):
3837
if self.is_empty():
39-
print "Priority queue is empty"
38+
print("Priority queue is empty")
4039
return False
4140
return self._pq_heap_.get_max()
4241

@@ -104,9 +103,9 @@ def test():
104103
mh_test.insert(priority)
105104
pq.insert(item, priority)
106105

107-
print pq.pq_arr()
108-
print mh_test.heap_arr()
109-
print "Element with highest priority: ", pq.get_item_with_highest_priority()
106+
print(pq.pq_arr())
107+
print(mh_test.heap_arr())
108+
print("Element with highest priority: ", pq.get_item_with_highest_priority())
110109

111110

112111
if __name__ == '__main__':
@@ -122,40 +121,40 @@ def test():
122121
5. Get the size and capacity of priority queue.
123122
6. Stop.
124123
"""
125-
print menu
124+
print(menu)
126125
while True:
127126
try:
128127
choice = input("Please enter your choice - ")
129128
except:
130-
print "Incorrect choice, please select from menu."
129+
print("Incorrect choice, please select from menu.")
131130
continue
132131
try:
133132
if choice == 1:
134-
item_priority = raw_input("Enter item & priority separated by a white-space - ")
133+
item_priority = input("Enter item & priority separated by a white-space - ")
135134
item_priority = item_priority.split(" ")
136135
item = item_priority[0].strip()
137136
priority = item_priority[1].strip()
138137
res = pq.insert(item, priority)
139-
print res
138+
print(res)
140139
continue
141140
if choice == 2:
142-
print pq.pq_print()
141+
print(pq.pq_print())
143142
continue
144143
if choice == 3:
145144
res = pq.get_item_with_highest_priority()
146-
print res
145+
print(res)
147146
continue
148147
if choice == 4:
149148
res = pq.delete_item_with_highest_priority()
150-
print res
149+
print(res)
151150
continue
152151
if choice == 5:
153-
print "Size : {} | Capacity: {}".format(pq.pq_size(), pq.pq_capacity())
152+
print("Size : {} | Capacity: {}".format(pq.pq_size(), pq.pq_capacity()))
154153
continue
155154
if choice == 6:
156155
break
157156
except Exception as ex:
158-
print "Error occurred while performing last operation(choice: {}):".format(choice)
159-
print ex.message, ex.args
157+
print("Error occurred while performing last operation(choice: {}):".format(choice))
158+
print(ex.message, ex.args)
160159

161-
print menu
160+
print(menu)

Tree/allPathsRootToLeaves.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from Tree.commons import insert, print_tree, is_leaf
2+
from copy import deepcopy
23

34
def all_paths_root_to_leaves_v1(root):
45
if root == None:
@@ -24,6 +25,17 @@ def all_paths_root_to_leaves_v2(root, path, path_len):
2425
all_paths_root_to_leaves_v2(root.left, path, path_len)
2526
all_paths_root_to_leaves_v2(root.right, path, path_len)
2627

28+
def all_paths_root_to_leaves_v3(root, path = []):
29+
if root is None: return
30+
path.append(root.key)
31+
if is_leaf(root):
32+
for elt in path:
33+
print(elt, end=',')
34+
print('\n')
35+
else:
36+
all_paths_root_to_leaves_v3(root.left, deepcopy(path))
37+
all_paths_root_to_leaves_v3(root.right, deepcopy(path))
38+
2739
# Driver program to test above function
2840
if __name__ == "__main__":
2941
""" Let us create following BST
@@ -51,4 +63,7 @@ def all_paths_root_to_leaves_v2(root, path, path_len):
5163
all_paths_root_to_leaves_v1(root)
5264

5365
print("\n-------- Using v2 ---------\n")
54-
all_paths_root_to_leaves_v2(root, [None] * 20, 0)
66+
all_paths_root_to_leaves_v2(root, [None] * 20, 0)
67+
68+
print("\n-------- Using v3 ---------\n")
69+
all_paths_root_to_leaves_v3(root)

Tree/distanceFromRoot.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@ def distance_from_root_v2(root, key, level=0):
3232
distance_v2 = level
3333
return level
3434

35-
left = distance_from_root_v2(root.left, key, level+1)
35+
ld = distance_from_root_v2(root.left, key, level+1)
3636
# if key found in left-subtree, return it.
37-
if left != -1:
38-
return left
37+
if ld != -1:
38+
return ld
3939
# if key is not found in left-subtree, try searching for key in right-subtree
4040
else:
41-
right = distance_from_root_v2(root.right, key, level+1)
42-
return right
41+
rd = distance_from_root_v2(root.right, key, level+1)
42+
return rd
4343

4444

4545
def distance_from_root_v3(root, key, distance=0):

0 commit comments

Comments
 (0)