Python字符统计代码Bug:重复字符多次添加至list_of_letters数组
解决字符重复统计中重复添加的问题
问题分析
原代码在处理重复次数相同的字符时,判断逻辑存在漏洞:当字符i的重复次数等于当前最大值most时,会遍历list_of_letters中的每个元素z,只要z不等于i就执行append(i)。这会导致同一个字符被多次添加(例如输入hhello时,第二个l会被再次添加到列表中)。
修复后的代码
most = 0 list_of_letters = [] def remove(string): return "".join(string.split()) sentence = input('Enter a sentence or a word: ') new = remove(sentence) new = new.lower() for i in new: rep = 0 for n in new: if i == n: rep += 1 if rep > most: list_of_letters = [i] most = rep elif rep == most: # 直接判断字符是否已在列表中,不在则添加 if i not in list_of_letters: list_of_letters.append(i) print(list_of_letters) for index in list_of_letters: print(index, end=" ") print(f'is repeated the most at {most} times')
优化建议(可选)
原代码用双重循环统计字符重复次数,时间复杂度为O(n²),当输入文本较长时效率较低。可以使用Python内置的collections.Counter来简化统计,代码更简洁高效:
from collections import Counter def remove(string): return "".join(string.split()) sentence = input('Enter a sentence or a word: ') processed = remove(sentence).lower() # 统计每个字符的出现次数 char_counts = Counter(processed) # 获取最大出现次数 max_count = max(char_counts.values()) # 筛选出出现次数等于最大值的字符 most_common_chars = [char for char, count in char_counts.items() if count == max_count] print(f"{' '.join(most_common_chars)} is repeated the most at {max_count} times")
内容的提问来源于stack exchange,提问作者amoez200
相关产品推荐
相关产品推荐

