Help writing a code that returns the length of the shortest word in a string?

I’m trying to complete a challenge on Codewars that requires a code that returns the length of the shortest word in a string. My thought process is as follows:

  1. Count the number of letters in each word
  2. Return the length of the word that had the smallest number of letters

I was thinking of adding each word in the string to a list and then… I’m not sure? Can I use the len() function to count the length of each item in a list? How do I get Python to return the item with the smallest length?
Here is what I have so far:

def find_short(s): # your code here list_of_each_word = [] for word in s: list_of_each_word.append(word) for item in list_of_each_word:

Beneath line 6 I was thinking of writing length_of_word = len(item) but there are multiple items in the list of each word! Wouldn’t this just count the length of each word, add them, and assign it to that variable? Any help would be appreciated.

If ‘s’ is a string then you may need to look for a way to SPLIT it into separate words (your loop on line 4 will split ‘s’ into a list of individual characters).
When you’re iterating through them, you’ll need something to keep track of which is the smallest you’ve found so far. (yes, you can use len()). Then you can return that.

I like dabbling on that site too, but don’t get disheartened when you spend ages trying to solve something, write half a page of code and then see someone’s done it with barely one line.

1 Like