Whenever User Inputs, hits an Out Of Range Error

46 views Asked by At
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");

The code supposed to print YES if the 2 words are same length and have the same letters and NO if they don't.

Error hits at line 15: if((rawWord[x] == wordArray[z])):
IndexError: list index out of range

It works when

  1. Words are same length and same letters.
  2. Words are different length.
  3. Words are same length and all the letters are different.

It doesn't work when

  1. Words are same length and different letters but at least one letter is the same
1

There are 1 answers

1
doctorlove On BEST ANSWER

As I noted in a comment, you are looping over for z in range(0,len(rawWord)): but indexing into wordArray which you remove things from in the loop.

Always be worried if you are removing things you are looping over.

Can I suggest a better/more pythonic solution?

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

We can make yours work - don't forget to use your repeats count when you index into the wordArray on line 15. Or what was line 15. I have also removed some un-needed punctuation.

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