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

Python重复单词检测程序开发问题:现有代码仅能识别连续输入的重复项

问题排查
  • 变量名拼写错误:
    1. 定义的存储列表变量为list,但追加元素时错写为lista.append()
    2. 定义的临时变量为double,条件判断时错写为douple
  • 逻辑不符合需求:现有代码仅将当前输入的单词和上一次输入的单词做对比,只能识别连续重复的情况,没有遍历所有历史输入判断单词是否已经出现过
  • 不规范写法:使用Python内置关键字list作为自定义变量名,会覆盖内置的列表类型功能,可能引发后续错误
修改方案

将历史输入的单词存入集合(查询效率比列表更高),每次输入新单词后直接判断是否已存在于集合中即可,修改后的代码如下:

word_history = set()
while True:
    word = input("word: ")
    if word in word_history:
        print(f"You gave {len(word_history)+1} words")
        break
    word_history.add(word)

如果需要保留所有历史输入的顺序,也可以用列表实现:

word_history = []
while True:
    word = input("word: ")
    if word in word_history:
        print(f"You gave {len(word_history)+1} words")
        break
    word_history.append(word)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:45:02