3

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?

Ashish Karn
  • 1,127
  • 1
  • 9
  • 20

3 Answers3

2

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')
Neroksi
  • 1,301
  • 1
  • 12
  • 20
  • Thanks dude helped me a lot – Murad PETROSYAN Jul 17 '20 at 10:36
  • I've add an `if statement` to handle the `empty` string case. Programming is about thinking of all the worst cases :) . – Neroksi Jul 17 '20 at 10:39
  • Since we are in the Python > 3.8 era, I would suggest using the walrus operator (https://www.geeksforgeeks.org/walrus-operator-in-python-3-8/) to avoid calling `len()` twice. `if (n := len(i)) <= max:` ... `max = n` – alec_djinn Jul 17 '20 at 10:47
  • Calling `len` [cost nothing in python](https://stackoverflow.com/questions/1115313/cost-of-len-function), at least when it comes to builtin types like `list objects`. – Neroksi Jul 17 '20 at 11:00
1

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.

Aleksander Ikleiw
  • 2,549
  • 1
  • 8
  • 26
0

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"))
    
Raviraja
  • 1
  • 2