Word Chain Game
Implement a class WordChain for a word game: every word must start with the last letter of the word before it, and no word may be used twice. Write these methods:
WordChain()starts with an empty chain.play(word)tries to addwordto the end of the chain. The first word is always accepted. After that,wordis accepted only if it starts with the last letter of the last word in the chain and is not in the chain yet. Returnstrueifwordwas added; otherwise nothing changes and it returnsfalse.get_last_word()returns the last word in the chain, or""if the chain is empty.count_words()returns how many words are in the chain.get_longest_word()returns the longest word in the chain, and on a tie the one added first. Returns""if the chain is empty.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
WordChain()
play("apple") returns true
play("egg") returns true
play("goat") returns true
play("tea") returns true
play("apple") returns false
play("ant") returns true
get_longest_word() returns "apple"
count_words() returns 5
apple would follow tea by its first letter, but it is already in the chain, so it is refused. ant is accepted instead, and apple is still the longest word.
Constraints
wordhas1to8lowercase letters- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.