修复Python字典统计字符串数字频率功能的代码问题
修复数字频率统计Python代码
功能要求
- 通过函数参数接收字符串
text变量 - 初始化一个新字典
- 遍历字符串的每个字符,判断是否为数字
- 统计字符串中数字的频率,忽略空格、字母及标点符号
- 以数字为键(确保键唯一)、对应频率为值填充字典
- 返回该字典
错误代码示例
def count_numbers(text): # Initialize a new dictionary. dictionary = {} # Complete the for loop to iterate through each "text" character. for i in text: # Complete the if-statement using a string method to check if the # character is a number. if i == int: # Complete the if-statement using a logical operator to check if # the number is not already in the dictionary. if i in dictionary: # Use a dictionary operation to add the number as a key # and set the initial count value to zero. dictionary.update({text, i}) # Use a dictionary operation to increment the number count value # for the existing key. i += i return dictionary
问题分析
- 数字判断逻辑错误:用
i == int判断字符是否为数字完全无效,正确做法是使用字符串方法char.isdigit() - 条件逻辑颠倒:原代码中判断数字已在字典时执行新增操作,实际应该是数字不在字典时初始化计数,存在时累加
- 字典操作错误:
dictionary.update({text, i})语法错误且逻辑错误,初始化键值应该用num_counts[char] = 0 - 计数累加错误:
i += i是对字符本身进行拼接,而非对字典中的计数进行累加,应操作字典对应键的值
修复后的代码
def count_numbers(text): num_counts = {} for char in text: # 判断当前字符是否为数字 if char.isdigit(): # 若数字未在字典中,初始化计数为0 if char not in num_counts: num_counts[char] = 0 # 对应数字计数加1 num_counts[char] += 1 return num_counts
也可以用更简洁的写法(利用字典get方法简化逻辑):
def count_numbers(text): num_counts = {} for char in text: if char.isdigit(): num_counts[char] = num_counts.get(char, 0) + 1 return num_counts
测试验证
运行以下测试用例,输出与预期一致:
print(count_numbers("1001000111101")) # 预期输出: {'1': 7, '0': 6} print(count_numbers("Math is fun! 2+2=4")) # 预期输出: {'2': 2, '4': 1} print(count_numbers("This is a sentence.")) # 预期输出: {} print(count_numbers("55 North Center Drive")) # 预期输出: {'5': 2}
内容的提问来源于stack exchange,提问作者Kamil Siddiqui
相关产品推荐
相关产品推荐

