Created
July 29, 2015 20:53
-
-
Save oskar-j/fe4193be1386744b01ae to your computer and use it in GitHub Desktop.
Finds a dominant element of array in Python
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
# 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]) |
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
nice one, but I will do it with a dictionary ;-)