Tuesday, January 14, 2020

IslandT: Return the word with the longest length within a string using Python

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!



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...