diff --git a/algorithms/arrays/top_1.py b/algorithms/arrays/top_1.py index 71ac6b042..b3d302924 100644 --- a/algorithms/arrays/top_1.py +++ b/algorithms/arrays/top_1.py @@ -34,4 +34,17 @@ def top_1(arr): continue return result - \ No newline at end of file + +def top_1_v2(arr): + # 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 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):