Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A function longest_word(text) gives the longest word of a text, and when two words are equally long, the first one. List six inputs that you would test, with the expected answers.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Use the edge-case checklist: nothing, one, repeats, ties, strange.
| Input | Expected | Edge |
|---|---|---|
"" | "" (or None: decide!) | nothing |
"hello" | hello | one word |
"a bb ccc" | ccc | usual |
"cat dog" | cat | a tie: the first |
" spaced out " | spaced | extra spaces |
"end. start" | start | punctuation: is end. of length 4? |
Check. Two rules need a decision: what is the longest word of an empty text, and do the marks count as part of a word? Write the decision down, and test it. A function with no written rule has no right answer.
Answer: The six cases above, with the decisions for the empty text and for punctuation written down.
Log in to join the discussion.
Loading…