Skip to content

Commit

Permalink
Adding tests for max subseq. Now this will break.
Browse files Browse the repository at this point in the history
  • Loading branch information
skytreader committed Mar 24, 2016
1 parent 9a153ed commit 576d1dc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
19 changes: 14 additions & 5 deletions algorithms/max_subseq.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,28 @@ def max_subarray(numseq):
return find_max_subarray(numseq, 0, len(numseq) - 1)

def max_subarray_dp(numseq):
"""
Returns a tuple containing the start index of the max subarray, the end
index of the max subarray, and the sum over that subarray, in that order.
"""
maxjs = []
max_idxs = []
max_ends = []
max_starts = []

for idx, val in enumerate(numseq):
if idx != 0:
cont = maxjs[idx - 1] + numseq[idx]
if cont > numseq[idx]:
maxjs.append(cont)
max_idxs.append(maxj_idxs[idx - 1])
max_ends.append(idx)
max_starts.append(max_starts[idx - 1])
else:
maxjs.append(numseq[idx])
max_idxs.append(idx)
max_ends.append(idx)
max_starts.append(idx)
else:
maxjs.append(numseq[0])
max_idxs.append(0)
max_ends.append(0)
max_starts.append(0)

return (maxjs[-1], max_idxs[-1])
return (max_starts[-1], max_ends[-1], maxjs[-1])
15 changes: 14 additions & 1 deletion algorithms/tests/max_subseq_tests.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ..max_subseq import max_subarray, find_biased_max
from ..max_subseq import max_subarray, max_subarray_dp, find_biased_max

import unittest

Expand All @@ -19,3 +19,16 @@ def test_max_subarray(self):
self.assertEqual((1, 2, 50), max_subarray((-5, 40, 10)))
self.assertEqual((0, 0, -10), max_subarray([-10]))
self.assertEqual((3, 6, 55), max_subarray((5, 15, -30, 10, -5, 40, 10)))

def test_max_subarray_dp(self):
self.assertEqual((0, 1, 20), max_subarray((5, 15, -30, 10)))
# The example from the book
stocks = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
self.assertEqual((7, 10, 43), max_subarray_dp(stocks))
self.assertEqual((0, 1, 10), max_subarray_dp((7, 3)))
self.assertEqual((1, 1, 10), max_subarray_dp((-10, 10)))
self.assertEqual((0, 0, 10), max_subarray_dp((10, -10)))
self.assertEqual((0, 0, 10), max_subarray_dp([10]))
self.assertEqual((1, 2, 50), max_subarray_dp((-5, 40, 10)))
self.assertEqual((0, 0, -10), max_subarray_dp([-10]))
self.assertEqual((3, 6, 55), max_subarray_dp((5, 15, -30, 10, -5, 40, 10)))

0 comments on commit 576d1dc

Please sign in to comment.