Problem overview
The method longWords receives a list of strings, words, and an integer n. It returns a new list holding only the words that have more than n characters, in their original order.
With words = ["apple", "kiwi", "banana", "fig"] and n = 4 the result is ['apple', 'banana']. "apple" has 5 characters and "banana" has 6. "kiwi" has exactly 4, which is not more than 4, so it is left out, and "fig" is too short. When no word is long enough, as with ["hi", "to", "be"] and n = 3, the result is the empty list []. Repeated words stay repeated: ["go", "went", "gone", "went"] with n = 3 gives ['went', 'gone', 'went'].
Approach: build a new list
This is the basic filter pattern. Start with an empty list, look at each item once, and add the items that pass the test. The input list is never changed: the answer is a separate list.
The loop meets the words from first to last, and append adds at the end of the result, so the order of the input is kept without any extra work.
Step by step
- Create the empty list
result. It collects the words that pass. If none does, it stays empty, which is exactly the answer the lesson wants in that case. - Loop over
wordswithfor word in words. Each pass giveswordone string from the list. - Test the length.
len(word)is the number of characters, and the condition islen(word) > n. The comparison is strict, so a word with exactlyncharacters fails it. - Append the word inside the
if, so only words that passed are added. - Return
resultafter the loop, once every word has had its turn.
Tracing the first example
With n = 4, the loop looks at one word at a time:
word | len(word) | len(word) > 4 |
|---|---|---|
| apple | 5 | True |
| kiwi | 4 | False |
| banana | 6 | True |
| fig | 3 | False |
Only "apple" and "banana" are appended, in that order, so the function returns ['apple', 'banana']. The same pattern, a condition around an append, filters by any other rule too.
The solution in Python
class Solution:
def longWords(self, words: List[str], n: int) -> List[str]:
result = []
for word in words:
if len(word) > n:
result.append(word)
return result
A few details are worth noting:
- Indentation is the structure. The
appendline is indented under theif, which is indented under thefor. Thereturnlines up with thefor, so it runs once, after the loop ends. Indented one level further, it would sit inside the loop and return after the first word. lenworks on strings. It counts characters, the same way it counts the items of a list.appendchanges the list in place and returnsNone, so there is nothing to assign back.
Edge cases and common mistakes
- Using
>=instead of>. With["apple", "kiwi", "banana", "fig"]andn = 4that would keep "kiwi" too. - Returning inside the loop. The function would return after the first word, whether or not the rest are long enough.
n = 0. Every word has at least one letter, so every word is kept:longWords(["tree", "bee"], 0)returns['tree', 'bee'].- Removing words from
wordswhile looping over it. Deleting items from a list during aforloop over it skips elements. Building a separate result list avoids the problem.
Testing
words = ["apple", "kiwi", "banana", "fig"],n = 4gives['apple', 'banana'].words = ["hi", "to", "be"],n = 3gives[].words = ["go", "went", "gone", "went"],n = 3gives['went', 'gone', 'went'].words = ["tree", "bee"],n = 0gives['tree', 'bee'].
