Skip to content

Instantly share code, notes, and snippets.

@bogsio
Created October 28, 2013 19:37
Show Gist options
  • Save bogsio/7203178 to your computer and use it in GitHub Desktop.
Save bogsio/7203178 to your computer and use it in GitHub Desktop.
majority
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