Having an issue coming up with a script to get the longest word using len and not split()

"Write a function giving the longest word in a given text.

Your function should be named longest_word, take a single argument text and return a string which should be the longest word in the given text.

Beware: the given text can span several lines."
That is the prompt given and when i tried using split() it did not recognize the function

split is a method of str, so it’s text.split(), and that returns a list. Were you doing split(text) instead?

Was using text.split() but got a error asking if i meant next
The script I have so far

<<<def longest_word(text):
    longest_word =  max(text, key=len)
    return longest_word
    print(longest_word)>>>

The correction I get:
In the text:

Monty Python and the Holy Grail

you found 'M' as the longest word, while I find 'Python'.
Mind you I am prompted to start with <def longest_word(text):>

max(text, key=len) will iterate over the characters of a string and return the longest, but they all have a length of 1. You need to split the string into words and then find the longest.

If you really were using text.split() and you had a variable called text, that should work.

If it didn’t work, you must have done something wrong, but I can’t guess what because you don’t show us either the code that failed or the full error message, starting with the word “Traceback”.

The script you show is surrounded by <<< >>> which is wrong. That should give you a SyntaxError.

Your function was almost correct, you just need to split the text into words:

def longest_word(text):
    return max(text.split(), key=len)

My code:

def longest_word(text):
    return max(text.split(), key=len)
    print(longest_word)

The error I got:
I called your function as:

longest_word('')

Python exception

Traceback (most recent call last):
  File "HOME:/solution.py", line 2, in longest_word
    return max(text.split(), key=len)
ValueError: max() arg is an empty sequence

A ValueError indicates that a function or an operation received an argument of the right type, but an inappropriate value.

I do not recognize this error message. I am guessing that the problem is with the function max. Its docstring is:

‘’'max(iterable, [, default=obj, key=func]) → value max(arg1, arg2, args, *[, key=func]) → value

With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.‘’’

Exception raised on line 2 of file HOME:/solution.py.

       1| def longest_word(text):
    -->2|     return max(text.split(), key=len)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
       3|     print(longest_word)



    text:  ''
    len:  <builtin function len>
    max:  <builtin function max>
    text.split:  <builtin method split of str object>

That is because:

>>> ''.split()
[]

and an empty list has no maximum.

The fix is to provide a default, just in case:

>>> max(text.split(), key=len, default=0)
0
1 Like

Was using text.split() but got a error asking if i meant next
The script I have so far

I’ve reformatted that a little:

def longest_word(text):
   longest_word =  max(text, key=len)
   return longest_word
print(longest_word)

The correction I get:
In the text:

Monty Python and the Holy Grail

you found 'M' as the longest word, while I find 'Python'.

Ah, you’re being beitten by the fact that Python strings are iterable,
which gets you single characters. And since Python doesn’t have a
standalone character type those characters are represented as single
character strings.

So…

Iterating the string in text gets you these strings as a result:

 'M'
 'o'
 'n'
 't'
 'y'
 ' '
 'P'
 'y'
 't'
 'h'
 'o'
 'n'

and so on. So the length of the first string (courtesy of your key=len
argument) is 1. So M is chosen as the initial “max” string. And none
of the following strings ('o', 'n' etc) are any longer so M is
kept as the result of the max() call.

What you probably want is to break the string up into “words”. Eg:

 words = text.split()
 longest_word =  max(words, key=len)

You should print out the value of words for debugging purposes:

 words = text.split()
 print("words =", words)
 longest_word =  max(words, key=len)

to see what’s going on there. (Of course remove the print() call
later.)

Cheers,
Cameron Simpson cs@cskk.id.au

definitely getting closer

def longest_word(text):
     words = text.split()
     longest_word =  max(words, key=len)
     print(longest_word)

but I get the correction:
I called your function as:

longest_word('Monty Python and the Holy Grail')

:::text
Python

Your function returned None, but is printing the expected string.

Your function should should return the value instead of printing it.

So of course I go:

def longest_word(text):
     words = text.split()
     longest_word =  max(words, key=len)
     return(longest_word)
     print(longest_word)
    

but now i’m met with:

Python exception

Traceback (most recent call last):
  File "HOME:/solution.py", line 3, in longest_word
    longest_word =  max(words, key=len)
ValueError: max() arg is an empty sequence

A ValueError indicates that a function or an operation received an argument of the right type, but an inappropriate value.

I do not recognize this error message. I am guessing that the problem is with the function max. Its docstring is:

‘’'max(iterable, [, default=obj, key=func]) → value max(arg1, arg2, args, *[, key=func]) → value

With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.‘’’

Exception raised on line 3 of file HOME:/solution.py.

       1| def longest_word(text):
       2|      words = text.split()
    -->3|      longest_word =  max(words, key=len)
                               ^^^^^^^^^^^^^^^^^^^
       4|      return(longest_word)



    words:  []
    len:  <builtin function len>
    max:  <builtin function max>

I am stumped to be honest

definitely getting closer

def longest_word(text):
    words = text.split()
    longest_word =  max(words, key=len)
    print(longest_word)

but I get the correction:
I called your function as:

longest_word('Monty Python and the Holy Grail')

Your function returned None, but is printing the expected string.

My function wasn’t a function. It was just the longest_word = max(....) part, modified. You still need to return a value from the
function etc.

So of course I go:

def longest_word(text):
    words = text.split()
    longest_word =  max(words, key=len)
    return(longest_word)
    print(longest_word)

NB: this has the print() after the return, so the print() will
never get called.

but now i’m met with:

Python exception

Traceback (most recent call last):
 File "HOME:/solution.py", line 3, in longest_word
   longest_word =  max(words, key=len)
ValueError: max() arg is an empty sequence

Move the print() to just after the split() call. That way you can
see the contents of words, which will help you debug.

You can’t take the max() of an empty sequence, so I’d guess that
text.split() is returning an empty list.

You’d better print text as well, before the .split:

 print("text =", repr(text))
 words = text.split()
 print("words =", words)
 longest_word =  max(words, key=len)
 print(longest_word)
 return(longest_word)

and see what happens.

A ValueError indicates that a function or an operation received an argument of the right type, but an inappropriate value.
I do not recognize this error message. I am guessing that the problem
is with the function max.

The message in the exception is max() arg is an empty sequence which
suggests that it is unhappy about being given an empty list of words.
What do you think the max() if no values should be? Rather than
taking a policy decision there, max() raises an exception for that
situation.

So you need to see what’s in owrds and figure out why it has whatever
it has.

Cheers,
Cameron Simpson cs@cskk.id.au

unfortunately words are a bunch of random strings the teacher has issued to test if it will work with multiple strings instead of specific ones

I’d expect text to be an arbitrary string. words should be the
nonwhitespace things found within it.

You need to:

  • verify for yourself that words was empty
  • check that it should have been empty for that particular text value
  • decide what your function should do or return for “no words”; this
    might be in your assignment specification or you may want to ask your
    teacher if this situation is unspecified
  • implement behaviour for that situation

The last point if the programming part. If “no words” is not a
supported situation, it may be enough to let the ValueError from
max() escape uncaught. On the other hand, if there is a defined value
you should return when there are no words, such as an empty string, then
you need to arrange to only use max() if there is at least one word,
and to return the defined value for “no words” otherwise.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Lol update Cameron,
I’m talking with the instructor and he is being cheeky by throwing ’ ’ as one of the sentences, currently trying to figure out how to incorporate that as a possibility in my script

def longest_word(text):
    if text =="":
        return("")
    words = text.split()
    longest_word =  max(words, key=len)
    return(longest_word)
    

Ended up being the code that passed

longest_word("   ")

The problematic situation is not the specific string "" but anything that makes an empty word list. Personally, I would be testing words, not text.

Oh, BTW, you don’t need brackets with return. You can just say:

return longest_word

Cheers,
Cameron

1 Like