Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import unittest
def find_mode(l):
if len(l) == 0:
return "ZeroLength"
l.sort()
sums = {}
for item in l:
if item in sums.keys():
sums[item] += 1
else:
sums[item] = 1
max_count = 0
max_item = l[0]
for k, v in sums.items():
if v > max_count:
max_count = v
max_item = k
return max_item
class TestFindMode(unittest.TestCase):
def test_empty(self):
self.assertEqual(find_mode([]), "ZeroLength")
def test_equal(self):
self.assertEqual(find_mode([1, 2]), 1)
def test_positives(self):
self.assertEqual(find_mode([2, 3, 5, 5, 5, 2, 4, 1, 3, 1]), 5)
def test_negatives(self):
self.assertEqual(find_mode([-1, -3, -1, -1, -2, -4, -7, -1]), -1)
if __name__ == '__main__':
unittest.main()
@dudepare
Copy link
Author

dudepare commented Oct 21, 2015

This should run O(N log N).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment