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
python4 anjali25
Sample Output
python25 anjali4
Sample Input
1python254
Sample Output
254python1
Sample Input
-1pyth-4on 5lear-3ning-2
Sample Output
5pyth4on 3lear2ning1
word = list();
numb = list();
line = input();
w = ''
n = ''
for i in line:
if '0' <= i <= '9':
n = n + i
if w != '':
word.append(w);
w = ''
else:
w = w + i
if n != '':
numb.append(int(n))
n = ''
if w != '':
word.append(w);
if n != '':
numb.append(int(n))
numb.sort(reverse=True)
ok = True
if '0' <= line[0] <= '9':
ok = False
i = 0
j = 0
while i < len(word) or j < len(numb):
if ok and i < len(word):
print(word[i], end='')
i += 1
if j < len(numb):
print(numb[j], end='')
j += 1
ok = True
Comments
Leave a comment