首页 > 解决方案 > (Python)有人可以帮我解决我的代码有什么问题吗?

问题描述

目标是返回字符串中出现的三的倍数。我只需要担心3、6、9的倍数并使用字典。例如,0939639 将返回 9,因为它出现了 3 次,而其他 3 的倍数出现的次数更少。

这是我的代码:

def count_threes(n):
    # Turning the number into a string
    x = len(str(n))

    # Setting the keys(multiple of threes) to 0 as the default count
    dict = {3: 0,
            6: 0,
            9: 0}

    # Loop through the string. If the number is a multiple of 3, it increments the key's value.
    for el in n:
        num = int(el)
        if num % 3 == 0 and num != 0:
            dict[el] += 1

    # Gets the maximum value and returns the key
    max_val = max(dict, key=dict.get)
    return max_val

我确实有一个给定的测试文件来测试该功能。我不断收到 KeyError,因此很难拔出钥匙。我似乎无法弄清楚我的代码哪里出错了。

标签: pythonloopsdictionary

解决方案


您的 dict 包含int作为键,并且el是一个字符串,因此您无法在 dict 中找到它,num用于访问 dict


另外,不要将其命名dict为字典构造函数关键字,您可以使用 adefaultdict来节省您编写初始值

from collections import defaultdict

def count_threes(value):
    counter = defaultdict(int)
    for char in value:
        num = int(char)
        if num and num % 3 == 0:
            counter[num] += 1

    return max(counter, key=counter.get)

print(count_threes('09396390000'))  # 9

推荐阅读