python - (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,因此很难拔出钥匙。我似乎无法弄清楚我的代码哪里出错了。
解决方案
您的 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
推荐阅读
- android - 如何在 Android 中查看附近地点的评分?
- sql - 添加一列并使用更新输入计算函数
- javascript - Timediff 减去 24 小时格式的 jquery 的中断时间
- javascript - 如何使用 CSS 裁剪和居中图像?
- vue.js - vuejs动态添加类
- aws-iot - 设备处于睡眠模式时的 AWS IoT 作业和 OTA 更新
- java - HackerRank 中的 Java If-Else,我的代码是好还是我能得到更好的问题解决方案
- reactjs - 检查用户是否打开了应用程序的多个选项卡
- c# - 通过gridview C#对卖家进行排序
- mobile - 如何开发支持安卓的游戏引擎