Created
October 28, 2013 19:37
-
-
Save bogsio/7203178 to your computer and use it in GitHub Desktop.
majority
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def majority(collection): | |
if not collection: | |
return None | |
# initialize a candidate | |
candidate = collection[0] | |
chances = 1 | |
# go through the rest of the elements | |
for c in collection[1:]: | |
# increase the chances | |
if c == candidate: | |
chances += 1 | |
# change the candidate | |
elif chances == 0: | |
candidate = c | |
chances = 1 | |
# decrease the chances | |
else: | |
chances -= 1 | |
# no viable candidate | |
if chances == 0: | |
return None | |
# check again | |
count = collection.count(candidate) | |
# do we have a majority? | |
if count > len(collection)/2: | |
return candidate | |
# nope, we don't | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment