Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Longest Word

Choose the longest whitespace-separated word with max and key=len. Students compare word lengths rather than alphabetic values and handle a tie or empty input.

IntermediatePhase 5 - Category 3: Word OperationsExample 4 of 10
find-longest-word.py
1# Take string input
2s = input("Enter a string: ")
3
4# Find longest word
5words = s.split()
6if len(words) > 0:
7 longest = max(words, key=len)
8 print(f"Longest word: {longest}")
9else:
10 print("No words found")

Output

Enter a string: Hello World Programming
Longest word: Programming

In this one

  • Compare lengths with key
  • Handle tied maxima
  • Guard empty collections

How it works

  1. 1

    Split the entered text.

  2. 2

    If nonempty, call max(words, key=len).

  3. 3

    Print that token or the no-words message.

Edge cases

What if two words tie?

What if two words tie?

The first longest token is chosen.

What if there are no words?

What if there are no words?

No words found is printed.

What's going on

After split, max(words, key=len) chooses a token by its length. Without key=len, max would compare string ordering instead.

The nonempty check avoids max on an empty sequence. If several words share the longest length, the first encountered maximum is returned. Punctuation remains in tokens and contributes to their measured length; this program does not clean dictionary words.

What if two words tie? The first longest token is chosen.

What if there are no words? No words found is printed.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does key=len change?

Pick an answer to check it.

Question 2

What if two words tie?

Pick an answer to check it.

Questions people ask

What if two words tie?

The first longest token is chosen.

What if there are no words?

No words found is printed.

What does key=len change?

The basis of comparison to token length.