Simple challenge – eliminate all bugs from the supplied code so that the code runs and outputs the expected value. The output should be the length of the longest word, as a number. There will only be one ‘longest’ word.

Above is a question from CodeWars, we will create the below python function to perform the above task.

```def find_longest(string):

longest_list = string.split(' ')
longest = len(longest_list.pop(0))
for n in longest_list:
if len(n) > longest:
longest = len(n)
return longest
```
• First, the function above will split the string into a list.
• Then it will use the length of the first word to compare to the remaining words within a for’s loop.
• If the length of any word within that list is longer than the length of the first word then the larger length will be assigned to the ‘longest’ variable which means that length will replace the length of the first word.
• Finally, return the longest length.

This will be the last time we solve the solution on CodeWars as from now onward we will concentrate on creating a project in python. My next project is a video editing python program written in Python, so stay tuned!

Click to rate this post!
[Total: 1 Average: 5]

1. Maxime says:

Hi!
There’s a shorter and possibly more pythonic way to determine the longest word in a sentence.
text = “hello python world”
longest_word = sorted(text.split(), key=len)[-1]

1. IslandTropicalMen says:

Yes that will be a shorter solution, thank you

2. Martin P. says:

As the LENGTH of the longest word was asked, not the longest word itself:

# I skipped the trivial splitting… 😉

>>> a = [‘aaa’, ‘bbbb’, ‘c’, ‘dddddd’, ‘eeeee’] # example after splitting

>>> a
[‘aaa’, ‘bbbb’, ‘c’, ‘dddddd’, ‘eeeee’] # just to verify in REPL

>>> max(a, key=len) # just to show the longest word in REPL
‘dddddd’

>>> len(max(a, key=len)) # solution!
6

# fully integrated:
>>> len(max(text.split(), key=len))

# No need for sorted 😀