小能豆

Python function to find the highest frequency number

python

I’m working on a Python function that is supposed to return the number with the highest frequency in an array. In cases where two numbers or more have the same frequency, it should return the larger number.

However, I’m facing an issue with my current implementation.

def highest_rank(arr):
    count_num = {}
    for i in arr:
        if i not in count_num:
            count_num[i] = 0
        else:
            count_num[i] = arr.count(i)
    return max(count_num, key=count_num.get)

In the this example [9, 48, 1, 8, 44, 45, 32] , I expect the function to return 48 but it return 9


阅读 64

收藏
2023-11-29

共1个答案

小能豆

The issue with your current implementation is that you are updating the count of each number while iterating through the array, but you are returning the number with the maximum count outside the loop. This way, the count of the last encountered number in the array will overwrite the counts of the previous numbers.

To fix this, you should iterate through the array first to calculate the counts of each number and then find the number with the maximum count. Here’s an updated version of your function:

def highest_rank(arr):
    count_num = {}

    # Calculate counts of each number
    for i in arr:
        if i not in count_num:
            count_num[i] = 1
        else:
            count_num[i] += 1

    # Find the number with the maximum count and return it
    max_count_num = max(count_num, key=lambda x: (count_num[x], x))
    return max_count_num

# Example usage:
arr = [9, 48, 1, 8, 44, 45, 32]
result = highest_rank(arr)
print(result)

This implementation uses max with a custom key function that considers both the count and the value of the number. This way, if two numbers have the same count, the larger number will be chosen. In your example, it will correctly return 48.

2023-11-29