From 41f4b370bdf975dc2203b3c7e4163ad1a8cc596a Mon Sep 17 00:00:00 2001 From: beam Date: Tue, 27 Oct 2026 21:38:46 +0000 Subject: [PATCH] beam: add majority_element (Boyer-Moore) with verified tests --- wizard-work/beam/majority_element.py | 22 ++++++++++++++++++++++ wizard-work/beam/test_majority_element.py | 14 ++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 wizard-work/beam/majority_element.py create mode 100644 wizard-work/beam/test_majority_element.py diff --git a/wizard-work/beam/majority_element.py b/wizard-work/beam/majority_element.py new file mode 100644 index 0000000..3d14f06 --- /dev/null +++ b/wizard-work/beam/majority_element.py @@ -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 diff --git a/wizard-work/beam/test_majority_element.py b/wizard-work/beam/test_majority_element.py new file mode 100644 index 0000000..04b70a6 --- /dev/null +++ b/wizard-work/beam/test_majority_element.py @@ -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()