Answer to Question #234244 in Python for rajesh

Question #234244
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.

Input
The input will be a single line containing a string.

Output
The output should be a single line containing the modified string with all the numbers in string re-ordered in decreasing order.

Explanation
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

should pass all test cases i could able to do pass
1
Expert's answer
2021-09-07T02:10:50-0400
s = input()
n = []
tmp = ''
for i in range(len(s)):
	if s[i].isdigit():
		tmp += s[i]
		if (i+1 < len(s)):
			if not(s[i+1].isdigit()):
				n.append(tmp)
				tmp = ''
		else:
			n.append(tmp)
sort_n = sorted(n, reverse=True)
new_s = ''
for i in range(len(s)):
	if s[i].isdigit():
		tmp += s[i]
		if (i+1 < len(s)):
			if not(s[i+1].isdigit()):
				new_s += sort_n.pop()
	else:
		new_s += s[i]
print(new_s)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS