Home > Software engineering >  Find the length of last word of a string without using string methods - Python
Find the length of last word of a string without using string methods - Python

Time:04-20

I have a question where I have to find the length of last word of a string without using any string method. If string methods were allowed, I could have splitted based on space and can take the last word.

What I tried so far is below:

string = "Hello how are you"

lst = list(string)
print(lst)

last_word = ""
for i in reversed(lst):
    if i == ' ':
        break
    elif i != ' ':
        last_word  = i

    
print(last_word)    
print(len(last_word))

This works fine until there is no space after last word.

This fails when string = "Hello how are you " OR string = "Hello how are you "

CodePudding user response:

You can add a to the end and continue if you get consecutive :

string = "Hello how are you   "


last_word = ""
previous = " "
for i in reversed(string):
    if i == ' ' and previous == ' ':
        continue
    elif i == ' ':
        break
    else:
        last_word  = i
        previous = i

    
print(last_word[::-1)    
print(len(last_word))

Output:

you
3

Also, you don't need to convert the string to a list.

CodePudding user response:

Assuming you don't care about punctuation, how about just iterating from the back of the string to:

  1. Find the first non-whitespace character:
  2. Find the first whitespace character before the above character:

Note: Calling len on a string is O(1).

# Source: https://github.com/python/cpython/blob/738c19f4c5475da186de03e966bd6648e5ced4c4/Objects/unicodetype_db.h#L6151
UNICODE_WHITESPACE_CHARS = {0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C,
                            0x001D, 0x001E, 0x001F, 0x0020, 0x0085, 0x00A0,
                            0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004,
                            0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
                            0x2028, 0x2029, 0x202F, 0x205F, 0x3000}


def get_last_non_whitespace_index(sentence: str) -> int:
    sentence_length = len(sentence)
    i = sentence_length - 1
    while i >= 0:
        if ord(sentence[i]) not in UNICODE_WHITESPACE_CHARS:
            return i
        i -= 1
    return -1


def get_last_word_len(sentence: str) -> int:
    last_non_whitespace_index = get_last_non_whitespace_index(sentence)
    if last_non_whitespace_index == -1:
        return 0
    i = last_non_whitespace_index
    while i >= 0:
        if ord(sentence[i]) in UNICODE_WHITESPACE_CHARS:
            break
        i -= 1
    return last_non_whitespace_index - i


def main() -> None:
    print(f'{get_last_word_len("Hello how are you") = }')
    print(f'{get_last_word_len("Hello how are you ") = }')
    print(f'{get_last_word_len("Hello how are you  ") = }')
    print(f'{get_last_word_len("") = }')
    print(f'{get_last_word_len("a   ") = }')  # Whitespace is a tab character.


if __name__ == '__main__':
    main()

Output:

get_last_word_len("Hello how are you") = 3
get_last_word_len("Hello how are you ") = 3
get_last_word_len("Hello how are you  ") = 3
get_last_word_len("") = 0
get_last_word_len("a    ") = 1

CodePudding user response:

string ="  Hello how are you   "
string=string[::-1]
i=0
count=0
ans=0
while True:
  if string[i]==' ':
     count =1
  else:
     break
  i =1
for i in range(count,len(string)):
    if string[i]==' ':
       break
    else:
      ans =1
print(ans)
  • Related