dmjio
10/10/2012 - 7:08 PM

majority_finder.py

majority_finder.py

#find majority element of an array in one fell swoop O(n)
#input ('a','b','c') --> "No majority"
#input ('a', 'b', 'b') --> 'b'

def majorityfinder(A):
	counter = 0
	element = 0
	for i in A:
		if counter == 0:
			element = i
			counter = 1
		else:
			if element == i:
				counter += 1
			else:
				counter -= 1
	if counter > 1:
		return element
	else:
		return "No majority"