检查单个值或两个或更多模式

Checking For Single Value or Two or More Modes

我正在尝试让我的程序 return 一个值,如果它是单模则不带括号; return 如果它有两个或更多模式,则该值为列表,如果在给定列表中找不到模式,则打印一条消息。

def calculate_mode(numbers_list: list):

    frequency = {}

    mode = 0

    for num in numbers_list:
        frequency[num] = frequency.get(num, 0) + 1

    most_occurences = max(frequency.values())

    for key, value in frequency.items():
        if value == most_occurences:
            mode = key

    return mode


print(calculate_mode([10, 13, 5, 4, 17, 17]))

我想要实现的是没有括号的单位数模式 return。使用解包运算符 (*) 只会删除应该在列表中的模式。例如,[1] 应该是 1,但如果我要使用 * 运算符,它也会将 [1, 2] 更改为 1 2。如果在给定列表中没有找到模式,那么它应该只打印出一个给用户的消息。

举几个例子:

>>> calculate_mode([10, 13, 5, 4, 17])
No Mode Found!

>>> calculate_mode([10, 13, 5, 4, 17, 17])
17

>>> calculate_mode([10, 13, 5, 4, 4, 17, 17])
[4, 17]

您的代码将 return 在存在多种模式时仅是单一模式(列表中的最后一个),而在不存在模式时是列表中的最后一个数字,因为您已将模式声明为整数并且在 for 循环中覆盖它,对于后者你没有检查是否不存在模式。

我建议的涵盖测试用例的答案是:

def calculate_mode(numbers_list: list):

    frequency = {}

    mode = []

    for num in numbers_list:
        frequency[num] = frequency.get(num, 0) + 1

    most_occurences = max(frequency.values())
    
    if most_occurences > 1: 
        for key, value in frequency.items():
            if value == most_occurences:
                mode.append(key)
    else:
        return('No Mode Found!')

    if len(mode)==1:
        return(mode[0])
    return mode

print(calculate_mode([10, 13, 5, 4, 17])) # Output: No Mode Found!
print(calculate_mode([10, 13, 5, 4, 17, 17])) # Output: 17
print(calculate_mode([10, 13, 5, 4, 4, 17, 17])) # Output: [4, 17]

您的代码return只有一种模式。即,最后一种模式。因此,每当值与 most_occurences 匹配时,将键插入列表并 return 列表。

对代码进行以下更改。

def calculate_mode(numbers_list: list):
    frequency = {}
    for num in numbers_list:
        frequency[num] = frequency.get(num, 0) + 1
    most_occurences = max(frequency.values())
    return [key for key, value in frequency.items() if value == most_occurences]

试试这个:

def calculate_mode(numbers_list: list):
    frequency = {}
    mode = []

    for num in numbers_list:
        frequency[num] = frequency.get(num, 0) + 1
        
    most_occurences = max(frequency.values())
    
    mode = [key for key, value in frequency.items() if value == most_occurences]    
    
    
    if len(mode) == len(numbers_list):
        return 'No Mode Found!'
    elif len(mode)==1 :
        return mode[0]
    else:
        return mode

print(calculate_mode([10, 13, 5, 4, 17])) # Output: No Mode Found!
print(calculate_mode([10, 13, 5, 4, 17, 17])) # Output: 17
print(calculate_mode([10, 13, 5, 4, 4, 17, 17])) # Output: [4, 17]

输出:

No Mode Found!
17
[4, 17]