Given a string sentence, rearrange the words in the sentence so that they are sorted by their length in ascending order.
If two words have the same length, they keep their original relative order.
Preserve the original casing and punctuation of each word. Words are separated by single spaces.
Function Signature
def arrange_by_length(sentence: str) -> str:
Rules
-
A word is a maximal run of non-space characters. Punctuation attached to a word is part of it and counts toward its length (
"Python!"
has length 7).
-
Words of equal length appear in the output in the same order as in the input.
-
The output separates words with single spaces and has no leading or trailing spaces.
Constraints
-
1 <= len(sentence) <= 10^4
-
sentence
consists of English letters, spaces, and the punctuation characters
.,!?;:
.
-
Words are separated by single spaces.
-
There are no leading or trailing spaces.
Examples
Input: sentence = "The quick brown fox jumps over the lazy dog"
Output: "The fox the dog over lazy quick brown jumps"
The lengths are 3 for "The", "fox", "the" and "dog", 4 for "over" and "lazy", and 5 for "quick", "brown" and "jumps". Within each length group the words keep the order they had in the sentence.
Input: sentence = "I love programming in Python!"
Output: "I in love Python! programming"
The lengths are 1 ("I"), 2 ("in"), 4 ("love"), 7 ("Python!") and 11 ("programming"). The exclamation mark stays attached to "Python!" and counts toward its length.
Input: sentence = "Go now, or stay."
Output: "Go or now, stay."
"Go" and "or" both have length 2 and keep their input order. "now," has length 4 and "stay." has length 5, because the comma and the period are counted.