Given a string, assuming the string is numbers only, rearrange the string to that it is the greatest possible number.
Below is my solution to the problem above. I'd like feedback mainly on the algorithm, as I wrote this up very quickly. I used comprehension syntax to find the largest num, which I'm trying to use more. Any other feedback is appreciated as well.
def largest_number(string: str) -> str:
"""
Given a string, organize the numbers such as the
rearrangement is now the largest possible number
"""
string = list(string)
largest = ""
for _ in string:
largest_num = str(max([int(num) for num in string]))
largest += largest_num
string[string.index(largest_num)] = -1
return largest
if __name__ == '__main__':
# Test Cases #
assert largest_number("12345") == "54321"
assert largest_number("4689123") == "9864321"
assert largest_number("9") == "9"
assert largest_number("1923") == "9321"
"".join(sorted(string), reverse=True)
is the best way to do it. \$\endgroup\$