Python实现lexicographics函数统计每行单词最大最小平均值问题求助
修改方案
核心问题说明
- 最小单词数初始值错误:初始值设为0,若所有行单词数都大于0,最小值永远无法被正确覆盖
- 最小值判断逻辑错误:误使用累计总词数
wordCount做比较,应该用当前行的单词数len(words) - 缺少Decimal类型转换,且函数未按要求返回结果元组
修正后代码
from decimal import Decimal def lexicographics(to_analyze): lines = 0 total_words = 0 max_words = 0 # 初始最小单词数设为无穷大,方便后续更新更小值 min_words = float('inf') line_list = to_analyze.split("\n") for line in line_list: lines += 1 current_word_num = len(line.split()) total_words += current_word_num # 更新最大值 if current_word_num > max_words: max_words = current_word_num # 更新最小值 if current_word_num < min_words: min_words = current_word_num # 计算平均值并转Decimal类型 avg_words = Decimal(total_words) / Decimal(lines) return (max_words, min_words, avg_words)
测试验证
运行测试用例:
print(lexicographics('''Don't stop believing, Hold on to that feeling.'''))
输出结果和预期一致:(5, 3, Decimal('4'))
内容的提问来源于stack exchange,提问作者glitch
相关产品推荐
相关产品推荐

