【发布时间】:2016-12-22 13:39:46
【问题描述】:
userInput = input();
for x in range(0,len(userInput)):
if(userInput[x] == " "):
spaceValue = x;
rawWord = userInput[0:spaceValue];
secWord = userInput[spaceValue+1:];
wordArray = [];
repeats = len(rawWord); #NEW VAR
if (len(rawWord) == len(secWord)):
for x in range(0,len(rawWord)):
wordArray.append(secWord[x]);
for x in range(0,len(rawWord)):
for z in range(0,len(rawWord)):
if((rawWord[x] == wordArray[z])): #Line 15 #repeats insted of wordArray[z]
wordArray.remove(rawWord[x]);
repeats = repeats - 1;
break;
if(len(wordArray) == 0):
print("YES");
else:
print("NO");
else:
print("NO");
如果两个单词长度相同且字母相同,则代码应打印 YES,否则打印 NO。
第 15 行出现错误: if((rawWord[x] == wordArray[z])):
IndexError: list index out of range
当
- 单词长度相同且字母相同。
- 字词长度不同。
- 单词长度相同且所有字母都不同。
当它不起作用时
- 单词长度相同且字母不同但至少有一个字母相同
【问题讨论】:
-
必须是
len(...) - 1。如果是len(...),它将过去。 -
顺便说一句,
range(0, len(userInput))==range(len(userInput)) -
你说的是哪个
len(...),有很多。全部? -
您正在循环访问
for z in range(0,len(rawWord)):并索引到wordArray您从循环中删除的内容。 -
@doctorlove 所以每当我删除一个值时,我需要少循环 1 次?
标签: python python-3.x outofrangeexception