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

Find Shortest Word

Find the shortest token with Python min and key=len. Students guard empty input, compare lengths, and predict first-occurrence behavior when several words tie.

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

Output

Enter a string: Hello World Programming
Shortest word: Hello

In this one

  • Select by minimum length
  • Keep first tied results
  • Retain punctuation in tokens

How it works

  1. 1

    Split s and check for tokens.

  2. 2

    Call min with key=len.

  3. 3

    Print the selected token or empty-input feedback.

Edge cases

What if two shortest words tie?

What if two shortest words tie?

The first encountered one is selected.

Are punctuation marks stripped?

Are punctuation marks stripped?

No. They remain part of token length.

What's going on

split provides nonempty whitespace-delimited tokens. min(words, key=len) evaluates lengths without replacing the words themselves.

The selected word is printed, not its length. Equal shortest lengths keep the first encountered token. Punctuation counts as part of the token, so a standalone punctuation mark can win. The empty-input branch avoids an invalid min call.

What if two shortest words tie? The first encountered one is selected.

Are punctuation marks stripped? No. They remain part of token length.

Quiz

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

Question 1

What does min return here?

Pick an answer to check it.

Question 2

What if two shortest words tie?

Pick an answer to check it.

Questions people ask

What if two shortest words tie?

The first encountered one is selected.

Are punctuation marks stripped?

No. They remain part of token length.

What does min return here?

A selected word.