Finding the shortest string in a string of words i

2019-03-03 14:28发布

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. This is what I did but mincount does neither increment nor set up to 0 at the end of each string. What is wrong with it?

def find_short(s):
    min=99
    for i in s:
        mincount = 0
        for j in i:
            print(j)
            mincount += 1
            print(mincount)
        if (mincount < min):
            min = mincount
    return min 

4条回答
Bombasti
2楼-- · 2019-03-03 14:47

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-03-03 14:47

You can use min with a key function:

# split the string by spaces and pick the min based on the lenght of splitted string
# Example:

string = "I eat apples"
final = min(string.split(), key = lambda x: len(x))

print(final)
# >>> I
查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-03 14:52
line = "I eat apples"
mins = min(len(word) for word in line.split())
print(mins)

line.split() will split line into list of words and then just finding the minimum length

查看更多
倾城 Initia
5楼-- · 2019-03-03 14:55

A function to estabilish the lenght of the smallest word in a text

def lenmin(text):
    return len(min(text.split()))

lenmin("I eat apples")

This will return 1

Using lambda

>>> lenmin = lambda t: len(min(t.split()))
>>> lenmin("you eat apples")
2
查看更多
登录 后发表回答