You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复Python歌手统计代码在IDLE中的运行错误

代码错误修复

核心错误

最后一行函数调用时参数拼写错误:print(favoriteSinger(n,song))里的song应该是songs,这会触发NameError,因为不存在名为song的变量。

另外,函数参数n在当前逻辑中没有被使用,属于冗余参数,可根据需求选择移除或添加输入校验(比如确保输入的歌曲列表长度等于n)。

修复后的代码

保留n参数的版本(仅修正拼写错误)

def favoriteSinger(n, songs):
    singer_counts = {}
    max_count = 0
    for singer in songs:
        singer_counts[singer] = singer_counts.get(singer, 0) + 1
        max_count = max(max_count, singer_counts[singer])

    favorite_singers = 0
    for singer, count in singer_counts.items():
        if count == max_count:
            favorite_singers += 1

    return favorite_singers

n = int(input())
songs = list(map(int, input().split()))

print(favoriteSinger(n, songs))  # 修正拼写错误:song → songs

移除冗余n参数的版本

def favoriteSinger(songs):
    singer_counts = {}
    max_count = 0
    for singer in songs:
        singer_counts[singer] = singer_counts.get(singer, 0) + 1
        max_count = max(max_count, singer_counts[singer])

    favorite_singers = 0
    for singer, count in singer_counts.items():
        if count == max_count:
            favorite_singers += 1

    return favorite_singers

n = int(input())
songs = list(map(int, input().split()))

# 可选:添加输入长度校验
if len(songs) != n:
    print("输入的歌曲数量与指定数量不匹配")
else:
    print(favoriteSinger(songs))

内容的提问来源于stack exchange,提问作者AKHIL LANKALAPALLI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:15:02