用 Python 计算出现频率最高的元素的频率
pythonserver side programmingprogramming更新于 2025/12/26 12:28:17
假设我们有一个名为 nums 的数字列表,我们必须找到出现频率最高的元素并获取该元素出现的次数。
因此,如果输入为 [1,5,8,5,6,3,2,45,7,5,8,7,1,4,6,8,9,10],则输出将为 3,因为数字 5 出现了三次。
为了解决这个问题,我们将遵循以下步骤 −
- max:= 0
- length:= nums 的大小
- 对于范围为 0 到长度-2 的 i,执行
- count:= 1
- 对于范围为 i+1 到长度-1 的 j,执行
- 如果 nums[i] 与 nums[j] 相同,则
- count := count + 1
- 如果 nums[i] 与 nums[j] 相同,则
- 如果 max < count,则
- max:= count
- 返回 max
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): max=0 length=len(nums) for i in range(0,length-1): count=1 for j in range(i+1,length): if(nums[i]==nums[j]): count+=1 if(max<count): max=count return max ob = Solution() nums = [1,5,8,5,6,3,2,45,7,5,8,7,1,4,6,8,9,10] print(ob.solve(nums))
输入
[1,5,8,5,6,3,2,45,7,5,8,7,1,4,6,8,9,10]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

