beam: add majority_element (Boyer-Moore) with verified tests
This commit is contained in:
1 parent
d3f3772558
commit
41f4b370bd
2 files changed
+36
No files matched your search
@@ -0,0 +1,22 @@
|
|||||||
|
"""Boyer-Moore majority vote: element appearing > n/2 times, or None."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any, Iterable, Optional
|
||||||
|
|
||||||
|
|
||||||
|
def majority(nums: Iterable[Any]) -> Optional[Any]:
|
||||||
|
arr = list(nums)
|
||||||
|
cand = None
|
||||||
|
count = 0
|
||||||
|
for x in arr:
|
||||||
|
if count == 0:
|
||||||
|
cand = x
|
||||||
|
count = 1
|
||||||
|
elif x == cand:
|
||||||
|
count += 1
|
||||||
|
else:
|
||||||
|
count -= 1
|
||||||
|
if not arr:
|
||||||
|
return None
|
||||||
|
if arr.count(cand) > len(arr) // 2:
|
||||||
|
return cand
|
||||||
|
return None
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import unittest
|
||||||
|
from majority_element import majority
|
||||||
|
|
||||||
|
class TestMajority(unittest.TestCase):
|
||||||
|
def test_basic(self):
|
||||||
|
self.assertEqual(majority([1,1,2]), 1)
|
||||||
|
self.assertEqual(majority([2,2,1,1,1]), 1)
|
||||||
|
self.assertIsNone(majority([1,2,3]))
|
||||||
|
self.assertIsNone(majority([]))
|
||||||
|
self.assertEqual(majority([5]), 5)
|
||||||
|
self.assertEqual(majority([1,1,1,2,2,2,2]), 2)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user