每当用户输入时,命中超出范围错误

时间:2016-12-22 13:39:46

标签: python python-3.x outofrangeexception

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");

如果2个单词的长度相同并且字母相同,那么该代码应打印YES。如果不是,则为NO。

错误点击第15行: if((rawWord[x] == wordArray[z])):
IndexError:列表索引超出范围

  

它适用于

  1. 字词相同长度相同字母
  2. 字词长度
  3. 字词相同长度所有字母不同
  4.   

    时不起作用
    1. 字词相同长度不同字母至少一个字母相同

1 个答案:

答案 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")