如何修改Python函数以返回按字母排序的最冷门爱好列表?
修复Python函数
find_least_popular_hobbies以返回最冷门爱好列表 需要实现Python函数find_least_popular_hobbies(data: str) -> list,要求返回按字母排序的最冷门爱好列表。
当前函数实现如下:
def find_least_popular_hobbies(data: str) -> list: new_dict = create_dictionary(data) # creates a dictionary where the key is the name and the value is the hobby sorted_dict = sort_dictionary(new_dict) # sorts the dictionary values alphabetically new_list = [] for value in sorted_dict.items(): for ele in value[1]: new_list.append(ele) count = [(x, new_list.count(x)) for x in new_list] return count
当前问题
该函数返回包含重复统计项的元组列表(例如[(hobby1, count), (hobby1, count), ...]),但期望输出是按字母排序的最冷门爱好列表,比如示例输入应返回['dance', 'flowers', 'puzzles', 'tennis']。
修改方案
要实现需求,需要完成去重统计爱好次数、筛选最小次数爱好、按字母排序这几个核心步骤,以下是两种可行的修改实现:
方案1:使用collections.Counter(简洁高效)
from collections import Counter def find_least_popular_hobbies(data: str) -> list: new_dict = create_dictionary(data) # 生成键为姓名、值为爱好列表的字典 # 提取所有爱好到一个列表中 all_hobbies = [] for hobbies in new_dict.values(): all_hobbies.extend(hobbies) # 统计每个爱好的出现次数 hobby_counts = Counter(all_hobbies) # 获取最小的出现次数 min_count = min(hobby_counts.values()) # 筛选出所有出现次数等于最小值的爱好 least_popular = [hobby for hobby, count in hobby_counts.items() if count == min_count] # 按字母顺序排序后返回 return sorted(least_popular)
方案2:手动统计(无需额外导入)
def find_least_popular_hobbies(data: str) -> list: new_dict = create_dictionary(data) # 生成键为姓名、值为爱好列表的字典 # 手动统计每个爱好的出现次数 hobby_counts = {} for hobbies in new_dict.values(): for hobby in hobbies: hobby_counts[hobby] = hobby_counts.get(hobby, 0) + 1 # 获取最小的出现次数 min_count = min(hobby_counts.values()) # 筛选出所有出现次数等于最小值的爱好 least_popular = [hobby for hobby, count in hobby_counts.items() if count == min_count] # 按字母顺序排序后返回 return sorted(least_popular)
修改说明
- 移除了原代码中冗余的
sorted_dict步骤:统计爱好次数无需提前对字典值排序,减少不必要的性能消耗。 - 替换低效的重复统计:原代码用
new_list.count(x)会对每个爱好遍历整个列表,时间复杂度高;改用Counter或手动字典统计,只需遍历一次所有爱好。 - 明确筛选逻辑:先找到最小出现次数,再筛选对应爱好,最后按字母排序得到符合要求的结果。
内容的提问来源于stack exchange,提问作者QLimbo
相关产品推荐
相关产品推荐

