🕯️ Magic Note
When you sort a string of digits, Python arranges them in ascending order based on their Unicode code points. For digits ‘0’ to ‘9’, this matches numerical order. The smallest digit comes first, the largest last. Index [-1] always gives the final element. Together, they extract the maximum digit without loops or conditions.
- Works for both positive and negative integers, but negative signs become ‘-‘ which sorts before digits
- Returns a string, convert with int() if you need a number
- Alternative: max(str(n)) is simpler and more direct
- For the smallest digit, use [0] instead of [-1]
| Input Number | Convert to String | Sorted | Largest Digit |
|---|---|---|---|
| 583291 | “583291” | [“1″,”2″,”3″,”5″,”8″,”9”] | “9” |
| 9427 | “9427” | [“2″,”4″,”7″,”9”] | “9” |
| 55555 | “55555” | [“5″,”5″,”5″,”5″,”5”] | “5” |
| 10203 | “10203” | [“0″,”0″,”1″,”2″,”3”] | “3” |
| 9876543210 | “9876543210” | [“0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9”] | “9” |
Python
# Finding the largest digit using sorted
n = 583291
largest = sorted(str(n))[-1]
print(largest)
# Output: 9
Python
# Simpler approach with max()
n = 583291
largest = max(str(n))
print(largest)
# Output: 9
# Much cleaner than sorted()[-1]
Python
# Getting both smallest and largest digits
n = 749218
digits = sorted(str(n))
smallest = digits[0]
largest = digits[-1]
print(f”Smallest: {smallest}, Largest: {largest}”)
# Output: Smallest: 1, Largest: 9
print(f”All digits in order: {”.join(digits)}”)
# Output: All digits in order: 124789
- Forgetting to convert the number to a string, causing TypeError: ‘int’ object is not iterable
- Using sorted(n) instead of sorted(str(n))
- Not realizing that the result is a string, then using it in a numeric context without converting with int()
⚡ Whisper
Chaos hides order. Scattered digits wait for a hand to sort them. Line them up from smallest to largest. The one at the end was always the ruler. Quietly, patiently, the top number appears. The mess becomes music.