easy +10 pts

Count words in a sentence

Count the words in a given sentence, handling extra spaces and empty input.

Write a function `count_words(sentence)` that takes a string `sentence` and returns the number of words in it. A word is defined as a maximal sequence of non-whitespace characters. For example, the sentence "Hello world" has 2 words. The sentence may contain leading, trailing, or multiple spaces between words; these should be ignored. If the sentence is empty or contains only whitespace, the function should return 0.

Constraints

The input string `sentence` can be any Python string, including empty. Its length is at most 10^5 characters. The function should run in O(n) time and O(n) space, where n is the length of the input.

Example

>>> count_words("Hello world")
2
>>> count_words("   This   is   a   test.   ")
4
>>> count_words("")
0
>>> count_words("   ")
0
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider using the built-in string method `split()` without arguments, which splits on any whitespace and handles multiple spaces automatically.
The `split()` method returns a list of words, so the answer is just the length of that list.
For an empty string or whitespace-only string, `split()` returns an empty list, so its length is 0.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.