python codekatas solutions | Cell 1 | Cell 3 | Search

The last_word_length function takes a string as input and returns the length of its last word. It does this by counting non-space characters from the end of the string until it encounters a space.

Cell 2

def last_word_length(text):
    """Given a string of words separated by spaced, return length of last word."""
    i = len(text)-1
    while i >= 0 and text[i] == ' ':
        i -= 1
    count = 0
    while i >= 0 and text[i] != ' ':
        i -= 1
        count += 1
    return count

assert last_word_length('') == 0
assert last_word_length('last   ') == 4
assert last_word_length('string  of  words') == 5
print('All passed!')

What the code could have been:

python
def last_word_length(text: str) -> int:
    """
    Given a string of words separated by spaces, returns the length of the last word.
    
    Args:
        text (str): The input string.
    
    Returns:
        int: The length of the last word.
    """
    # Remove trailing whitespace to simplify the search for the last word
    text = text.rstrip()
    
    # If the string is empty, return 0
    if not text:
        return 0
    
    # Find the index of the last space before the last word
    last_space_index = text.rfind(' ')
    
    # If no space is found, the entire string is the last word
    if last_space_index == -1:
        return len(text)
    
    # Return the length of the last word
    return len(text) - last_space_index - 1


assert last_word_length('') == 0
assert last_word_length('last   ') == 4
assert last_word_length('string  of  words') == 5
print('All passed!')

last_word_length function

Purpose

Returns the length of the last word in a given string.

Parameters

Returns

The length of the last word in the string.

Functionality

  1. It starts from the end of the string (len(text)-1) and moves backwards until it encounters a non-space character.
  2. It counts the number of non-space characters until it encounters a space.
  3. It returns this count, which represents the length of the last word.

Example Use Cases