diff --git a/math/add.py b/math/add.py new file mode 100644 index 000000000000..604075ab8ad1 --- /dev/null +++ b/math/add.py @@ -0,0 +1,12 @@ +def add(a: int, b: int) -> int: + """ + Return sum of two integers + + >>> add(2, 3) + 5 + >>> add(-1, 1) + 0 + """ + if not isinstance(a, int) or not isinstance(b, int): + raise ValueError("Inputs must be integers") + return a + b diff --git a/searches/boyer_moore_majority_vote.py b/searches/boyer_moore_majority_vote.py new file mode 100644 index 000000000000..b11592fa1a1e --- /dev/null +++ b/searches/boyer_moore_majority_vote.py @@ -0,0 +1,23 @@ +def majority_element(nums: list[int]) -> int: + """ + Find majority element using Boyer-Moore Voting Algorithm + https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm + + >>> majority_element([3, 3, 4]) + 3 + >>> majority_element([2, 2, 1, 1, 2, 2, 2]) + 2 + """ + + if not nums: + raise ValueError("List cannot be empty") + + candidate = None + count = 0 + + for num in nums: + if count == 0: + candidate = num + count += 1 if num == candidate else -1 + + return candidate