0

I've been making a function to search through two lists and check if a character is in both lists.The error

"IndexError: list index out of range"

keeps coming up. I put this through python Tutor and it seems like the while loop is totally ignored.I'm coding this search without using the in function in an if statement. Any help would be much appreciated!

Here is my code:

aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOE"
userInputList = list(userInput)
letterExists = 0

while (letterExists < len(userInput)):
    for i in aList:
        if (i == userInputList[letterExists]):
            letterExists +=1

if (letterExists == len(userInput)):
        print("This word can be made using your tiles")
2
  • use "if i in userInputList"...will work here since length differ here what you are referring in loop Commented Apr 4, 2018 at 11:45
  • you don't need to make a list out of the user input. Commented Apr 4, 2018 at 11:48

3 Answers 3

1

letterExists < len(userInput) only guarantees that there is 1 more letter that can be processed, but you may iterate more than 1 time by means of the for loop.

By the way, you can write this condition very nicely using set:

the_set = set(["B", "S", ...])
if(all(x in the_set for x in userInput)):
   ...
Sign up to request clarification or add additional context in comments.

Comments

0

Looking at your code and without trying to do better, I found that a break is missing after the incrementation of letterExists. Here is the fixed code:

aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOE"
userInputList = list(userInput)
letterExists = 0

while (letterExists < len(userInput)):
    for i in aList:
        if (i == userInputList[letterExists]):
            letterExists +=1
            break

if (letterExists == len(userInput)):
        print("This word can be made using your tiles")

However, a better pythonic solution is the following (same as xtofl's answer):

aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOF"

a = all([letter in aList for letter in userInput])

if (a):
    print("This word can be made using your tiles")

Comments

0

You can use python magic and write it like this:

len([chr for chr in userInput if chr in aList]) == len(userInput)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.