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

使用.split()的Python程序对特定输入计数错误,求助修正(禁集合/字典)

问题解决

问题分析

你的代码存在两个核心问题:

  1. 违反任务要求:使用了字典,而题目明确禁止使用集合和字典。
  2. 逻辑不符合你预期的统计规则:原代码仅统计字面不同的单词,所以输入facebook face face book时输出3;但你认为正确结果是2,说明你要统计的是不包含其他输入单词作为子串的唯一单词(比如facebook包含face,因此不计入统计)。

符合要求的代码实现

以下代码完全不使用集合和字典,严格遵循任务要求,同时满足你的统计规则:

def unique_counter():
    words = input().lower().split()
    # 第一步:对单词去重(用列表实现)
    distinct_words = []
    for word in words:
        if word not in distinct_words:
            distinct_words.append(word)
    
    # 第二步:筛选出不包含其他任何单词的唯一单词
    valid_unique = []
    for current in distinct_words:
        contains_other = False
        for other in distinct_words:
            if other != current and other in current:
                contains_other = True
                break
        if not contains_other:
            valid_unique.append(current)
    
    print(len(valid_unique))

unique_counter()

代码说明

  1. 先将输入转为小写并拆分单词,避免大小写差异影响统计结果。
  2. 用列表distinct_words实现字面去重,确保每个单词只保留一次。
  3. 遍历去重后的单词,检查每个单词是否包含其他任意单词作为子串:
    • 若包含,则排除该单词;
    • 若不包含,则加入有效唯一单词列表。
  4. 最后输出有效唯一单词的数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:15:42