Finding the shortest string in a string of words in python

后端 未结 4 898
后悔当初
后悔当初 2021-01-28 02:30

I want to write a function that would return the length of the shortest string in a string of words. Sample: \"I eat apples\" would return 1 since \"I\" is the shorted string. T

4条回答
  •  有刺的猬
    2021-01-28 03:07

    I would suggest @pramod's answer if you want a quick and easy solution, but I will use your function and show you what happened.

    def find_shortest(string):
        smallest_length = 99
        for word in string.split():
            current_length = 0
            for letter in word:
                current_length += 1
            if current_length < smallest_length:
                smallest_length = min_length
        return smallest_length
    

    Changes

    • I renamed most of the variables to make their purpose clearer
      • Notably the variable min was renamed. Since min is already defined as a function, this may cause issues.
    • Changed for word in string to for word in string.split(). By default split() separates the string into a list based on whitespace. Previously you were simply iterating through every character, which is problematic.

    Note: smallest_length being set to 99 assumes that the length of the smallest word is 99 characters or less. Set it higher for larger words.

提交回复
热议问题