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");
错误点击第15行: if((rawWord[x] == wordArray[z])):
IndexError:列表索引超出范围
它适用于
时不起作用
答案 0 :(得分:0)
正如我在评论中所指出的那样,您正在循环for z in range(0,len(rawWord)):
,但会将其编入wordArray
,并将其从循环中移除。
如果要删除正在循环的内容,请务必担心。
我可以建议更好/更多的pythonic解决方案吗?
from itertools import permutations
userInput = input()
words = userInput.split(' ')
rawWord = words[0]
otherWords = [''.join(p) for p in permutations(words[1])]
if rawWord in otherWords:
print("YES")
else:
print("NO")
我们可以让你的工作 - 当你在第15行的wordArray
索引时不要忘记使用你的重复计数。或者第15行是什么。
我还删除了一些不需要的标点符号。
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)
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-repeats]): #Line 15
wordArray.remove(rawWord[x])
repeats = repeats - 1
break;
if(len(wordArray) == 0):
print("YES")
else:
print("NO")
else:
print("NO")