Divide and Conquer. Find the majority of element in array

2024/7/7 6:10:14

I am working on a python algorithm to find the most frequent element in the list.

def GetFrequency(a, element):
return sum([1 for x in a if x == element])def GetMajorityElement(a):n = len(a)if n == 1:return a[0]k = n // 2elemlsub = GetMajorityElement(a[:k])elemrsub = GetMajorityElement(a[k:])if elemlsub == elemrsub:return elemlsublcount = GetFrequency(a, elemlsub)rcount = GetFrequency(a, elemrsub)if lcount > k:return elemlsubelif rcount > k:return elemrsubelse:return None

I tried some test cases. Some of them are passed, but some of them fails.

For example, [1,2,1,3,4] this should return 1, buit I get None.

The implementation follows the pseudocode here: http://users.eecs.northwestern.edu/~dda902/336/hw4-sol.pdf The pseudocode finds the majority item and needs to be at least half. I only want to find the majority item.

Can I get some help? Thanks!

Answer

I wrote an iterative version instead of the recursive one you're using in case you wanted something similar.

def GetFrequency(array):majority = int(len(array)/2)result_dict = {}while array:array_item = array.pop()if result_dict.get(array_item):result_dict[array_item] += 1else:result_dict[array_item] = 1if result_dict[array_item] > majority:return array_item   return max(result_dict, key=result_dict.get)

This will iterate through the array and return the value as soon as one hits more than 50% of the total (being a majority). Otherwise it goes through the entire array and returns the value with the greatest frequency.

https://en.xdnf.cn/q/120308.html

Related Q&A

Scraping dynamic webpage using Python

I am trying to scrape following dynamically generated webpage https://www.governmentjobs.com/careers/capecoral?page=1 Ive used requests, scrapy, scrapy-splash but I simply get page source code and I d…

numba cuda deprecation error : how to update my code?

Im running a jupyter notebook frome here : https://github.com/noahgift/nuclear_powered_command_line_tools/blob/master/notebooks/numba-cuda.ipynb The docs of current numba/cuda is here : https://numba.r…

reverse nested dicts using python

I already referred these posts here, here and here. I have a sample dict like as shown below t = {thisdict:{"brand": "Ford","model": "Mustang","year": …

python how to generate permutations of putting a singular character into a word

No idea how to word this so the title sucks my bad, Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it. So if my word was Cats, I want to get every permu…

Selenium Scraping Javascript Table

I am stuggling to scrape as per code below. Would apprciate it if someone can have a look at what I am missing? Regards PyProg70from selenium import webdriver from selenium.webdriver import FirefoxOp…

PYTHON REGEXP to replace recognized pattern with the pattern itself and the replacement?

Text- .1. This is just awesome.2. Google just ruined Apple.3. Apple ruined itself! pattern = (dot)(number)(dot)(singlespace)Imagine you have 30 to 40 sentences with paragraph numbers in the above patt…

How can I extract the text between a/a? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How do I access classes and get a dir() of available actions?

I have been trying to get access to available functions for a Match Object from re.search. I am looking for a way to do that similar to how I could do dir(str) and I can find .replace.This is my dir() …

Python - IndexError: list index out of range

Why would data[entities][urls][0][expanded_url] would produce IndexError: list index out of range error? I understand what this error means but cant see why? perhaps too sleepy at 2 am? Please helpd…

Python: Use Regular expression to remove something

Ive got a string looks like thisABC(a =2,b=3,c=5,d=5,e=Something)I want the result to be likeABC(a =2,b=3,c=5)Whats the best way to do this? I prefer to use regular expression in Python.Sorry, somethi…