Skip to content

Instantly share code, notes, and snippets.

@oskar-j
Created July 29, 2015 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskar-j/fe4193be1386744b01ae to your computer and use it in GitHub Desktop.
Save oskar-j/fe4193be1386744b01ae to your computer and use it in GitHub Desktop.
Finds a dominant element of array in Python
# Majority Element of an Array (Moore’s Algorithm)
# If n is odd then it should appear at least (n+1)/2 times
# If n is even then it should appear at least (n/2) + 1 times
def dominant(A):
x = None
count = 0
for i in A:
if count == 0:
x = i
count += 1
elif i == x:
count += 1
else:
count -= 1
return (x, count)
print dominant([3, 1, 3, 4, 3, 9, 3])
print dominant([1, 1, 4, 3, 4, 1, 1, 9])
@michal-slezak-dev
Copy link

nice one, but I will do it with a dictionary ;-)

@Endote
Copy link

Endote commented Jan 24, 2022

Your code assumes that the first element of the array is the most frequent one,
when you give something else at the beginning it is incorrect.

and print statement needs parenthesis of its own.

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment