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
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.
Changes
min
was renamed. Sincemin
is already defined as a function, this may cause issues.for word in string
tofor word in string.split()
. By defaultsplit()
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.You can use
min
with a key function:line.split()
will split line into list of words and then just finding the minimum lengthA function to estabilish the lenght of the smallest word in a text
This will return 1
Using lambda