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.
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!')
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!')
Returns the length of the last word in a given string.
text
(str): A string of words separated by spaces.The length of the last word in the string.
len(text)-1
) and moves backwards until it encounters a non-space character.last_word_length('')
returns 0, because there are no words.last_word_length('last ')
returns 4, because 'last' is the last word.last_word_length('string of words')
returns 5, because 'words' is the last word.