From b7dc6581e1a05dc213dcc9ee511cba187fec4aca Mon Sep 17 00:00:00 2001 From: edward Date: Sat, 15 Sep 2018 20:18:45 +0800 Subject: [PATCH 1/2] add_top_1_dp --- algorithms/arrays/top_1.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/algorithms/arrays/top_1.py b/algorithms/arrays/top_1.py index dea9aa2f9..b31622355 100644 --- a/algorithms/arrays/top_1.py +++ b/algorithms/arrays/top_1.py @@ -30,3 +30,19 @@ def top_1(arr): continue return result + + +def top_1_dp(arr): + # DP Solution + # Once Iteration + ans = [] + mostcount = 0 + count = {} + for x in arr: + count[x] = count.get(x, 0) + 1 + if count[x] > mostcount: + ans = [x] + mostcount = count[x] + elif count[x] == mostcount: + ans.append(x) + return ans \ No newline at end of file From 4232ecd448ff8f4dc65dc46c1e32c1c183e6842c Mon Sep 17 00:00:00 2001 From: edward Date: Sat, 15 Sep 2018 20:41:30 +0800 Subject: [PATCH 2/2] add top_1_v2 & testcase --- algorithms/arrays/top_1.py | 3 +-- tests/test_array.py | 7 +++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/algorithms/arrays/top_1.py b/algorithms/arrays/top_1.py index b31622355..9850fc08f 100644 --- a/algorithms/arrays/top_1.py +++ b/algorithms/arrays/top_1.py @@ -32,8 +32,7 @@ def top_1(arr): return result -def top_1_dp(arr): - # DP Solution +def top_1_v2(arr): # Once Iteration ans = [] mostcount = 0 diff --git a/tests/test_array.py b/tests/test_array.py index 3fd6e0882..072b8fb26 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -15,6 +15,7 @@ max_ones_index, trimmean, top_1, + top_1_v2, limit, n_sum ) @@ -338,6 +339,12 @@ def test_top_1(self): self.assertListEqual(top_1([1 , 1, 2, 2, 3]), [1, 2]) self.assertListEqual(top_1([1, 2, 3, 324, 234, 23, 23, 1, 23, 23]), [23]) +class TestTop1V2(unittest.TestCase): + + def test_top_1_v2(self): + self.assertListEqual(top_1_v2([1 , 1, 2, 2, 3]), [1, 2]) + self.assertListEqual(top_1_v2([1, 2, 3, 324, 234, 23, 23, 1, 23, 23]), [23]) + class TestLimit(unittest.TestCase):