python寻找多数元素,分而治之。查找数组中的大多数元素

博客内容讨论了一个Python算法,旨在找到列表中的多数元素,即出现次数超过列表长度一半的元素。现有代码存在一些问题,无法正确处理某些测试用例。经过一系列编辑和改进,提出了一个新的解决方案,该方案首先计算每个元素的频率,然后返回出现次数最多的元素。当出现频率相同时,返回数值较大的元素。最后,指出了提供的伪代码可能解决的是元素占比超过50%的情况,而不仅仅是出现次数最多的情况。
摘要由CSDN通过智能技术生成

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 // 2

elemlsub = GetMajorityElement(a[:k])

elemrsub = GetMajorityElement(a[k:])

if elemlsub == elemrsub:

return elemlsub

lcount = GetFrequency(a, elemlsub)

rcount = GetFrequency(a, elemrsub)

if lcount > k:

return elemlsub

elif rcount > k:

return elemrsub

else:

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!

解决方案def majority_element(a):

return max([(a.count(elem), elem) for elem in set(a)])[1]

EDIT

If there is a tie, the biggest value is returned. E.g: a = [1,1,2,2] returns 2. Might not be what you want but that could be changed.

EDIT 2

The pseudocode you gave divided into arrays 1 to k included, k + 1 to n. Your code does 1 to k - 1, k to end, not sure if it changes much though ? If you want to respect the algorithm you gave, you should do:

elemlsub = GetMajorityElement(a[:k+1]) # this slice is indices 0 to k

elemrsub = GetMajorityElement(a[k+1:]) # this one is k + 1 to n.

Also still according to your provided pseudocode, lcount and rcount should be compared to k + 1, not k:

if lcount > k + 1:

return elemlsub

elif rcount > k + 1:

return elemrsub

else:

return None

EDIT 3

Some people in the comments highligted that provided pseudocode solves not for the most frequent, but for the item which is present more that 50% of occurences. So indeed your output for your example is correct. There is a good chance that your code already works as is.

EDIT 4

If you want to return None when there is a tie, I suggest this:

def majority_element(a):

n = len(a)

if n == 1:

return a[0]

if n == 0:

return None

sorted_counts = sorted([(a.count(elem), elem) for elem in set(a)], key=lambda x: x[0])

if len(sorted_counts) > 1 and sorted_counts[-1][0] == sorted_counts[-2][0]:

return None

return sorted_counts[-1][1]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值