Longest Word
In Doc2Doc, we have a search function to find the longest word in a document.
Last updated
In Doc2Doc, we have a search function to find the longest word in a document.
Last updated
Complete the find_longest_word
function without a loop. It accepts string inputs, document
, and optional longest_word
, which is the current longest word and defaults to an empty string.
Check if the first word is longer than the current longest_word
, then recur for the rest of the document.
Ensure there are no potential .
Assume that a "word" means a series of any consecutive non-whitespace characters. For example, longest_word("How are you?")
should return the string "you?"
.
Function Signature:
Purpose:
Searches through the document string to determine the longest word.
Parameters:
document
: The remaining text to search through.
longest_word
: The current longest word found (defaults to an empty string).
Base Case:
Explanation:
If the document is empty, there's nothing left to search.
Callout: The recursion stops here and returns the longest word found so far.
Splitting the Document:
Explanation:
Splits the document into a list of words, but only into two parts:
The first word.
The rest of the document (everything after the first word).
Callout: This ensures we only work with one word at a time and pass the remainder to the next recursive call, avoiding loops.
Checking and Updating the Longest Word:
Explanation:
If there is at least one word:
Compare the length of the first word (words[0]
) with the current longest_word
.
Update longest_word
if the first word is longer.
Callout: This conditional is the key comparison step to determine which word is longer.
Recursion for the Rest of the Document:
Explanation:
If there is more than one element in words
, it means there is a remainder of the document.
Recursively call find_longest_word
on the remaining text (words[1]
), passing along the updated longest_word
.
Callout: This is the recursive step that processes the rest of the document one word at a time.
Final Return:
Explanation:
If no remainder is found (i.e., words
contains only one word), return the current longest_word
.
Callout: This covers the case where the document was just one word, or when we've processed all words.