Python, not supported between instances of 'int' and 'str' error

Viewed 103

here is my function

def find_short(s):
    s = s.split()
    max = len(s[0])
    for i in s:
        if len(i) <= max:
            max = i
    return max

    print(find_short("bitcoin take over the world maybe who knows perhaps"))

What is incorrect here?

3 Answers

You've forgotten to add some len to i in your for loop. See my anser that corrects this error.

def find_short(s):
    s = s.split()
    if not s:
       return 0,""
    max = len(s[0])
    argmax = s[0]
    for i in s:
        if len(i) <= max:
            max = len(i)
            argmax = i
    return max,argmax

print(find_short("bitcoin take over the world maybe who knows perhaps"))
(3, 'who')

That is because the max = i line makes the max variable a string. You can not compare the string and the int value. That comes from you assigning the i which is an element of s variable to the max.

In the above code you have made two errors,

  • using max, max is an inbuilt function of python so use some other name like maxi.

  • at last after the first condition check in the if class, if the condition satisfies the max (which u used) will get updated with the string i, if you want to print small letter in the string use the following code.

     def find_short(s):
         s = s.split()
         maxi = len(s[0])
         for i in s:
             if len(i) <= maxi:
                 maxi = len(i)
                 ans = i
         return len(ans)
     print(find_short("bitcoin take over the world maybe who knows perhaps"))
    

    or else if you want to print length of small letter in the string use the following code.

     def find_short(s):
         s = s.split()
         maxi = len(s[0])
         for i in s:
             if len(i) <= maxi:
                 maxi = len(i)
                 ans = i
         return len(ans)
     print(find_short("bitcoin take over the world maybe who knows perhaps"))
    
Related