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
- Words are same length and same letters.
- Words are different length.
- Words are same length and all the letters are different.
It doesn't work when
- Words are same length and different letters but at least one letter is the same
As I noted in a comment, you are looping over
for z in range(0,len(rawWord)):
but indexing intowordArray
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?
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.