Rearrange Numbers in String
Given a string, write a program to re-arrange all the numbers appearing in the string in decreasing order. Note: There will not be any negative numbers or numbers with decimal part.
The input will be a single line containing a string.
The output should be a single line containing the modified string with all the numbers in string re-ordered in decreasing order.
For example, if the given string is "I am 5 years and 11 months old", the numbers are 5, 11. Your code should print the sentence after re-ordering the numbers as "I am 11 years and 5 months old".
Sample Input
I am 5 years and 11 months old
Sample Output
I am 11 years and 5 months old
Sample Input
3times4is12
Sample output
12times4is3
user_str = input('Enter your string: ')
numbers = ''.join([i if i.isdigit() else ' ' for i in user_str ]).split()
numbers_rep = list(map(int, numbers))
numbers_rep.sort(reverse = True)
numbers_rep = list(map(str, numbers_rep))
output_str = user_str
# use the problem conditions: not be any numbers with decimal part
for i in numbers:
output_str = output_str.replace(i,'1.1',1)
for i in numbers_rep:
output_str = output_str.replace('1.1',i,1)
print(output_str)
Comments
Leave a comment