beam: add majority_element (Boyer-Moore) with verified tests

This commit is contained in:
beam committed 2026-10-27 21:38:46 +00:00
1 parent d3f3772558
commit 41f4b370bd
2 files changed
+36

No files matched your search

+22
View File
@@ -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
+14
View File
@@ -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()