Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moore #3539

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Moore #3539

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Moore's algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def majority_element(nums):
"""
Returns the majority element in a given list using Moore's Voting Algorithm.

Args:
nums (list): List of integers.

Returns:
int: Majority element, if it exists. None otherwise.
"""
# initialize variables
candidate = None
count = 0

# iterate through list
for num in nums:
if count == 0:
# set new candidate
candidate = num
count += 1 if num == candidate else -1

# verify candidate is actually the majority element
if nums.count(candidate) > len(nums) // 2:
return candidate
else:
return None
nums = [2,2,1,1,1,2,2]
print(majority_element(nums)) # output: 2

nums = [3,3,4,2,4,4,2,4,4]
print(majority_element(nums)) # output: 4

nums = [1,2,3,4,5]
print(majority_element(nums)) # output: None