Skip to content
Advertisement

Function to determine whether a word is valid according to some rules

The function is_valid_word should return True if word is in the word_list and is entirely composed of letters available in the hand. Otherwise, returns False. It does not mutate hand or word_list.

JavaScript

I notice that if I use return True instead of pass in the code, it does not read other letters in word. I understand why. Are there other ways to implement the function without pass?

Also can the multiple else statements be avoided?

Advertisement

Answer

To get rid of the first else negate the conditions changing

JavaScript

To

JavaScript

For the second else you can just get rid of it, rewriting

JavaScript

as

JavaScript

Since the function always returns early when inside of the if statement (because of the return True), then we don’t have to actually write out the else statement as the only way for us to not return early and move past the if statement is if the word is not in the wordlist. I.e. we get the behavior of an else without have to write out an else.


Also instead of

JavaScript

You can use a counter.

JavaScript
Advertisement