为何这段判断isogram的代码始终返回true?
Isogram判断代码始终返回True的问题分析
问题描述
这段代码本应接收任意字符串输入,判断该单词是否为isogram(即不含重复字母的单词),但实际运行时总是返回true,请分析原因。
原代码
# word input and defining variables word = list(str(input())) letter = 0 letters = len(word) x = 0 while letter <= letters: # while loop to repeat once for each letter if word.count([letter]) > 1: # checks if the letter is repeated more than once x += 1 letter += 1 # letter is raised by one so it moves onto the next place in the list else: letter += 1 # printing result if x == 0: print("true") else: print("false")
问题原因
核心错误:count方法的参数使用完全错误
代码里用word.count([letter]),这里的letter是循环的索引值(0、1、2...),把它放到列表[letter]里,相当于在word这个字符列表中查找包含该索引数字的子列表。但输入字符串转成的列表里全是单个字符,根本不存在子列表,所以count永远返回0,导致if条件永远不成立,x始终为0,最后必然输出true。
正确的写法应该是用word.count(word[letter]),这样才是统计当前索引对应的字母在列表中出现的次数。循环边界错误
while letter <= letters中,letters是word的长度,比如单词长度为5,索引范围是0-4,当letter等于5时,word[letter]会触发索引越界。正确的边界应该是letter < letters,确保循环只遍历有效索引。
修正后的示例代码
word = list(str(input()).lower()) # 转小写,因为isogram通常不区分大小写 letter = 0 letters = len(word) x = 0 while letter < letters: current_char = word[letter] if word.count(current_char) > 1: x += 1 letter += 1 print("false" if x > 0 else "true")
内容的提问来源于stack exchange,提问作者Dim
相关产品推荐
相关产品推荐

