Skip to content

Commit 996ea7f

Browse files
committed
Add automated tests
1 parent f2f1944 commit 996ea7f

21 files changed

+88
-46
lines changed
File renamed without changes.

legacy2.7/daily_coding_problem_01_05.py legacy/daily_coding_problem_01_05.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ def coding_problem_01(stack):
1515
Note: with Python lists, you could instead islice(chain.from_iterable(izip(l, reversed(l))), len(l))
1616
"""
1717
queue = deque([]) # stack S:[1,2,3,4,5], queue Q:[]
18-
for cnt in xrange(len(stack) - 1): # move stack into queue. S:[1], Q:[5,4,3,2]
18+
for cnt in range(len(stack) - 1): # move stack into queue. S:[1], Q:[5,4,3,2]
1919
queue.append(stack.pop())
20-
for cnt in xrange(len(queue) / 2):
20+
for cnt in range(len(queue) // 2):
2121
stack.append(queue.popleft()) # S:[1,5], Q:[4,3,2]
22-
for cnt2 in xrange(len(queue) - 1): # rotate last element to front, S:[1,5], Q:[2,4,3]
22+
for cnt2 in range(len(queue) - 1): # rotate last element to front, S:[1,5], Q:[2,4,3]
2323
queue.append(queue.popleft())
2424
stack.append(queue.popleft()) # S:[1,5,2], Q:[4,3]
2525
if queue:
@@ -39,7 +39,7 @@ def coding_problem_02(l):
3939
"""
4040
forward = [1] * len(l)
4141
backward = [1] * len(l)
42-
for idx in xrange(1, len(l)):
42+
for idx in range(1, len(l)):
4343

4444
forward[idx] = forward[idx - 1] * l[idx - 1]
4545
backward[-idx - 1] = backward[-idx] * l[-idx]

legacy2.7/daily_coding_problem_06_10.py legacy/daily_coding_problem_06_10.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def coding_problem_06():
77
Example:
88
99
>>> l = coding_problem_06()
10-
>>> for cnt in xrange(0, 4):
10+
>>> for cnt in range(0, 4):
1111
... l.add(cnt)
1212
>>> l.get(2) == 2
1313
True
@@ -51,7 +51,7 @@ def add(self, val):
5151

5252
def get(self, index):
5353
current_index, previous_index, current_node = self.head()
54-
for cnt in xrange(index + 1):
54+
for cnt in range(index + 1):
5555
previous_index, current_index = current_index, current_node.next_node(previous_index)
5656
current_node = self.memory[current_index]
5757
return current_node.val
@@ -147,14 +147,14 @@ def delayed_execution(f, ms):
147147
return f()
148148

149149
def hello(name):
150-
print 'Hello {}'.format(name)
150+
print('Hello {}'.format(name))
151151

152152
job = Thread(target=delayed_execution, args=(lambda: hello('from thread'), 0.01))
153153
job.start()
154154

155-
print 'Before'
155+
print('Before')
156156
time.sleep(0.02)
157-
print 'After'
157+
print('After')
158158

159159

160160
if __name__ == '__main__':

legacy2.7/daily_coding_problem_11_15.py legacy/daily_coding_problem_11_15.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def coding_problem_14():
108108
pi_approx = 3.0 # physicist $/pi$
109109
while True:
110110

111-
for cnt in xrange(10000):
111+
for cnt in range(10000):
112112

113113
inside += math.hypot(random.random(), random.random()) <= 1
114114

@@ -128,12 +128,12 @@ def coding_problem_15(sample_generator):
128128
>>> random.seed(0xBADC0FFE)
129129
>>>
130130
>>> def sample_gen_fun(n):
131-
... for x in xrange(n):
131+
... for x in range(n):
132132
... yield x
133133
>>>
134134
>>> num = 10
135135
>>> hist = [0] * num
136-
>>> for trials in xrange(5000):
136+
>>> for trials in range(5000):
137137
...
138138
... hist[coding_problem_15(sample_gen_fun(num))] += 1
139139
>>>

legacy2.7/daily_coding_problem_16_20.py legacy/daily_coding_problem_16_20.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def coding_problem_16(length):
1010
Example:
1111
1212
>>> log = coding_problem_16(10)
13-
>>> for id in xrange(20):
13+
>>> for id in range(20):
1414
... log.record(id)
1515
1616
>>> log.get_last(0)
@@ -156,7 +156,7 @@ def coding_problem_18(arr, k):
156156
>>> coding_problem_18([10, 5, 2, 7, 8, 7], 3)
157157
[10, 7, 8, 8]
158158
"""
159-
for cnt in xrange(k - 1):
159+
for cnt in range(k - 1):
160160
arr = [max(value, other) for value, other in zip(arr[:-1], arr[1:])]
161161

162162
return arr
@@ -170,7 +170,7 @@ def coding_problem_19(costs):
170170
"""
171171
best_cost = [0] * len(costs[0])
172172
for cost in costs: # add a house at a time
173-
for index in xrange(len(cost)): # best cost is the one for that color plus min cost between every other color
173+
for index in range(len(cost)): # best cost is the one for that color plus min cost between every other color
174174
best_cost[index] = cost[index] + min(best_cost[:index] + best_cost[index + 1:])
175175

176176
return min(best_cost)
@@ -215,10 +215,10 @@ def coding_problem_20(list_a, list_b):
215215
if len_b > len_a:
216216
list_a, list_b = list_b, list_a
217217

218-
for advance in xrange(abs(len_a - len_b)):
218+
for advance in range(abs(len_a - len_b)):
219219
list_a = list_a.next
220220

221-
for check in xrange(len_b):
221+
for check in range(len_b):
222222
if list_a is list_b:
223223
return list_a.value
224224

legacy2.7/daily_coding_problem_21_25.py legacy/daily_coding_problem_21_25.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,16 @@ def coding_problem_23(matrix, start, end):
6666
6767
>>> map = [[False, False, False, False], [True, True, False, True],
6868
... [False, False, False, False], [False, False, False, False]]
69-
>>> coding_problem_23(matrix, (3, 0), (0, 0))
69+
>>> coding_problem_23(map, (3, 0), (0, 0))
7070
7
7171
>>> map[1][2] = True # close off path
72-
>>> coding_problem_23(matrix, (3, 0), (0, 0)) # None
72+
>>> coding_problem_23(map, (3, 0), (0, 0)) # None
7373
"""
7474
coords = [(index_r, index_c) for index_r, row in enumerate(matrix)
7575
for index_c, element in enumerate(row) if not element]
7676

7777
current_distance = 0
78-
distances = [[None for col in xrange(len(matrix[0]))] for row in xrange(len(matrix))]
78+
distances = [[None for col in range(len(matrix[0]))] for row in range(len(matrix))]
7979
distances[start[0]][start[1]] = 0
8080
while True:
8181

@@ -177,7 +177,7 @@ def coding_problem_25(rexp, string):
177177

178178
if len(rexp) >= 2 and rexp[1] == '*':
179179

180-
for cnt in xrange(len(string)):
180+
for cnt in range(len(string)):
181181
if coding_problem_25(''.join([rexp[0]] * cnt) + rexp[2:], string):
182182
return True
183183

legacy2.7/daily_coding_problem_26_30.py legacy/daily_coding_problem_26_30.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,14 @@
1+
try:
2+
from future.utils import implements_iterator
3+
except ImportError:
4+
pass
5+
6+
try:
7+
from functools import reduce
8+
except ImportError:
9+
pass
10+
11+
112
def coding_problem_26(not_a_linked_list, k):
213
"""
314
Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be
@@ -15,19 +26,19 @@ def coding_problem_26(not_a_linked_list, k):
1526
k-buffer of the stream, would not be constant space. If you're reading this and have better ideas, let me know!
1627
"""
1728
iter_to_the_end = iter(not_a_linked_list)
18-
for _ in xrange(k):
19-
iter_to_the_end.next() # k is guaranteed < len(list)
29+
for _ in range(k):
30+
next(iter_to_the_end) # k is guaranteed < len(list)
2031

2132
result = []
2233
iter_lagging_behind = iter(not_a_linked_list)
2334
while True:
24-
result.append(iter_lagging_behind.next())
35+
result.append(next(iter_lagging_behind))
2536
try:
26-
iter_to_the_end.next()
37+
next(iter_to_the_end)
2738
except StopIteration:
2839
break
2940

30-
iter_lagging_behind.next() # gobble an element
41+
next(iter_lagging_behind) # gobble an element
3142
result.extend(iter_lagging_behind)
3243
return result
3344

legacy2.7/daily_coding_problem_31_35.py legacy/daily_coding_problem_31_35.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def coding_problem_32(exchange_matrix):
5858
Since floating point quantities are involved, we need to test for approximate equality.
5959
"""
6060
em = np.array(exchange_matrix) # ideally, we should test if the exchange_matrix is well-formed
61-
cem = np.vstack(em[0, :] / em[0, n] for n in range(len(em))) # computed exchange_matrix
61+
cem = np.vstack([em[0, :] / em[0, n] for n in range(len(em))]) # computed exchange_matrix
6262
return np.allclose(em, cem)
6363

6464

legacy2.7/daily_coding_problem_36_40.py legacy/daily_coding_problem_36_40.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def coding_problem_37(s):
2525
The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.
2626
You may also use a list or array to represent a set. Example:
2727
28-
>>> sorted([sorted(subset) for subset in coding_problem_37({1, 2, 3})], cmp=lambda a, b: cmp(len(a), len(b)))
28+
>>> sorted([sorted(subset) for subset in coding_problem_37({1, 2, 3})], key=len)
2929
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
3030
"""
3131
power_set = [[]]
@@ -82,7 +82,7 @@ def coding_problem_39(cells):
8282
8383
>>> gol = coding_problem_39(((0, 1), (1, 2), (2, 0), (2, 1), (2, 2)))
8484
>>> for _ in range(5):
85-
... print gol
85+
... print(gol)
8686
... gol.simulate()
8787
..*
8888
*.*

legacy2.7/daily_coding_problem_41_45.py legacy/daily_coding_problem_41_45.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def coding_problem_41(flights_db, starting_airport):
2121
return [starting_airport]
2222

2323
legs = [leg for leg in flights_db if leg[0] == starting_airport]
24-
for leg in sorted(legs, cmp=lambda la, lb: cmp(la[1], lb[1])):
24+
for leg in sorted(legs, key=lambda x: x[1]):
2525

2626
unused_legs = copy(flights_db)
2727
unused_legs.remove(leg)
@@ -139,7 +139,7 @@ def coding_problem_44(arr):
139139
Note2: [TODO] idea is here, but should avoid using .index(), which is a linear search. Committing as is for now.
140140
"""
141141
inversions = 0
142-
sorted_indexes = [xi[1] for xi in sorted(zip(arr, range(len(arr))), cmp=lambda x, y: cmp(x[0], y[0]))]
142+
sorted_indexes = sorted(range(len(arr)), key=lambda x: arr[x])
143143
for index in range(len(sorted_indexes)):
144144

145145
destination = sorted_indexes.index(index)

legacy2.7/daily_coding_problem_46_50.py legacy/daily_coding_problem_46_50.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ def coding_problem_47(prices):
3131
Here's the inefficient one-liner:
3232
3333
>>> prices = [9, 11, 8, 5, 7, 10]
34-
>>> max([max(prices[today + 1:]) - prices[today] for today in xrange(len(prices) - 1)])
34+
>>> max([max(prices[today + 1:]) - prices[today] for today in range(len(prices) - 1)])
3535
5
3636
"""
37-
max_future_price, max_profit = None, None
37+
max_future_price, max_profit = prices[-1], 0
3838
for index in range(len(prices) - 1, 0, -1):
3939
max_future_price = max(max_future_price, prices[index])
4040
max_profit = max(max_profit, max_future_price - prices[index - 1])
@@ -94,7 +94,7 @@ def coding_problem_49(arr):
9494
cumulative_sum += val
9595
cumulative_sums.append(cumulative_sum)
9696

97-
highest_peak, max_sum = None, 0
97+
highest_peak, max_sum = cumulative_sums[-1], 0
9898
for index in range(len(cumulative_sums) - 1, 0, -1):
9999
highest_peak = max(highest_peak, cumulative_sums[index])
100100
max_sum = max(max_sum, highest_peak - cumulative_sums[index - 1])

legacy/run_tests.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import importlib
2+
from pathlib import Path
3+
from doctest import testmod
4+
5+
6+
def run_tests(wild_path='daily_coding_problem_*.py', verbose=False):
7+
8+
for filename in sorted(Path(__file__).parent.glob(wild_path)):
9+
module = importlib.import_module(filename.stem)
10+
results = testmod(module, verbose=verbose)
11+
print(f'{filename.name}: {"FAIL" if results.failed else "PASS"}')
12+
13+
14+
if __name__ == '__main__':
15+
run_tests()

legacy2.7/run_tests.py

Whitespace-only changes.

problems/15/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ Example:
99
>>> random.seed(0xBADC0FFE)
1010

1111
>>> def sample_gen_fun(n):
12-
... for x in xrange(n):
12+
... for x in range(n):
1313
... yield x
1414

1515
>>> num = 10
1616
>>> hist = [0] * num
17-
>>> for trials in xrange(5000):
17+
>>> for trials in range(5000):
1818
... hist[coding_problem_15(sample_gen_fun(num))] += 1
1919

2020
>>> all(abs(float(h) / sum(hist) - 1.0 / len(hist)) < 0.01 for h in hist)

problems/15/problem_15.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ def coding_problem_15(sample_generator):
88
>>> random.seed(0xBADC0FFE)
99
1010
>>> def sample_gen_fun(n):
11-
... for x in xrange(n):
11+
... for x in range(n):
1212
... yield x
1313
1414
>>> num = 10
1515
>>> hist = [0] * num
16-
>>> for trials in xrange(5000):
16+
>>> for trials in range(5000):
1717
... hist[coding_problem_15(sample_gen_fun(num))] += 1
1818
1919
>>> all(abs(float(h) / sum(hist) - 1.0 / len(hist)) < 0.01 for h in hist)

problems/15/solution_15.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ def coding_problem_15(sample_generator):
1111
>>> random.seed(0xBADC0FFE)
1212
1313
>>> def sample_gen_fun(n):
14-
... for x in xrange(n):
14+
... for x in range(n):
1515
... yield x
1616
1717
>>> num = 10
1818
>>> hist = [0] * num
19-
>>> for trials in xrange(5000):
19+
>>> for trials in range(5000):
2020
... hist[coding_problem_15(sample_gen_fun(num))] += 1
2121
2222
>>> all(abs(float(h) / sum(hist) - 1.0 / len(hist)) < 0.01 for h in hist)

problems/23/solution_23.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ def coding_problem_23(matrix, start, end):
99
1010
>>> map = [[False, False, False, False], [True, True, False, True],
1111
... [False, False, False, False], [False, False, False, False]]
12-
>>> coding_problem_23(matrix, (3, 0), (0, 0))
12+
>>> coding_problem_23(map, (3, 0), (0, 0))
1313
7
1414
1515
>>> map[1][2] = True # close off path
16-
>>> coding_problem_23(matrix, (3, 0), (0, 0)) # None
16+
>>> coding_problem_23(map, (3, 0), (0, 0)) # None
1717
1818
"""
1919
coords = [(index_r, index_c) for index_r, row in enumerate(matrix)

problems/39/solution_39.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def coding_problem_39(cells):
1919
2020
>>> gol = coding_problem_39(((0, 1), (1, 2), (2, 0), (2, 1), (2, 2)))
2121
>>> for _ in range(5):
22-
... print gol
22+
... print(gol)
2323
... gol.simulate()
2424
..*
2525
*.*

problems/47/solution_47.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ def coding_problem_47(prices):
1111
Here's the inefficient one-liner:
1212
1313
>>> prices = [9, 11, 8, 5, 7, 10]
14-
>>> max([max(prices[today + 1:]) - prices[today] for today in xrange(len(prices) - 1)])
14+
>>> max([max(prices[today + 1:]) - prices[today] for today in range(len(prices) - 1)])
1515
5
1616
"""
17-
max_future_price, max_profit = None, None
17+
max_future_price, max_profit = prices[-1], 0
1818
for index in range(len(prices) - 1, 0, -1):
1919
max_future_price = max(max_future_price, prices[index])
2020
max_profit = max(max_profit, max_future_price - prices[index - 1])

problems/49/solution_49.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def coding_problem_49(arr):
1616
cumulative_sum += val
1717
cumulative_sums.append(cumulative_sum)
1818

19-
highest_peak, max_sum = None, 0
19+
highest_peak, max_sum = cumulative_sums[-1], 0
2020
for index in range(len(cumulative_sums) - 1, 0, -1):
2121
highest_peak = max(highest_peak, cumulative_sums[index])
2222
max_sum = max(max_sum, highest_peak - cumulative_sums[index - 1])

problems/run_tests.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import importlib
2+
from pathlib import Path
3+
from doctest import testmod
4+
5+
6+
def run_tests(wild_path='**/solution_*.py', verbose=False):
7+
8+
for filename in sorted(Path(__file__).parent.glob(wild_path)):
9+
module_name = '.'.join((filename.parent.name, filename.stem))
10+
module = importlib.import_module(module_name)
11+
results = testmod(module, verbose=verbose)
12+
print(f'{filename.name}: {"FAIL" if results.failed else "PASS"}')
13+
14+
15+
if __name__ == '__main__':
16+
run_tests()

0 commit comments

Comments
 (0)