Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to find majority element in a sequence of values using Boyer-Moore vote algorithm?

"""
Implementation of Boyer-Moore majority
vote algorithm.
Aim is to find the element with the majority
account (called majority element) in a 
sequence of values. 
Time complexity: O(n); Space complexity: O(1)
"""


def find_majority_elt(arr):
    # Find majority candidate using algorithm
    majority_candidate = -1
    votes = 0
    for elt in arr:
        if votes == 0:
            majority_candidate = elt
            votes = 1
        else:
            if(elt == majority_candidate):
                votes += 1
            else:
                votes -= 1
    return majority_candidate


def is_majority(candidate, array):
    # Confirm that candidate is majority
    n = len(array)
    if n == 0:
        return False
    count = 0
    for elt in array:
        if elt == candidate:
            count += 1
    return count > n // 2


values = [1, 1, 1, 2, 1, 3]
majority_elt = find_majority_elt(values)
# The below prints: Majority element is: 1
if is_majority(majority_elt, values):
    print("Majority element is:", majority_elt)
else:
    print("No majority element found")
Comment

PREVIOUS NEXT
Code Example
Python :: [Solved] TypeError: can’t multiply sequence by non-int of type str 
Python :: polarean share price 
Python :: vsc python close all functions 
Python :: pandas dataframe get number of columns 
Python :: save image url to png python 
Python :: sort json python 
Python :: jupyter notebook extensions 
Python :: convert number to binary python 
Python :: python parse json file 
Python :: neural network import 
Python :: how to empty a text file in python 
Python :: arithmetic python string 
Python :: nlargest 
Python :: one line input in python 
Python :: tf.contrib.layers.xavier_initializer() tf2 
Python :: python create random matrix 
Python :: migrate using other database django 
Python :: delete index in df 
Python :: change each line color as a rainbow python 
Python :: launch google chrome using python 
Python :: how to change the datatype of a row in pandas 
Python :: add percentage column pandas 
Python :: how to move a column in pandas dataframe 
Python :: dire Bonjour en python 
Python :: python print return code of requests 
Python :: how to auto update chromedriver selenium python 
Python :: python create folder if not exists 
Python :: change the color of the button on hovering tkinter 
Python :: openpyxl write in cell 
Python :: discord bot python meme command 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =