Answer to Question #204348 in Python for Praveen

Question #204348

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


Sample Input

I am 2 years and 3 months old. This sentence4 5should be 6rearr7anged8. If possible -9these negative-12 nums


Sample Output

I am 12 years and 9 months old. This sentence8 7should be 6rearr5anged4. If possible 3these negative2 nums



1
Expert's answer
2021-06-07T17:20:40-0400
import re
message = input()
message=message.replace('-', '')
wordsTokens= message.split()
integerNumbers=[int(num) for num in re.findall(r'\d+', message)]
unsortedIntegerNumbers=[int(num) for num in re.findall(r'\d+', message)]
integerNumbers.sort(reverse=True)
for i in range(0,len(wordsTokens)):
    if(len(unsortedIntegerNumbers)>0):
        index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
        previousIndex=-2
        while (len(unsortedIntegerNumbers)>0) and index!=-1 and index!=previousIndex:
            previousIndex=index
            index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
            wordsTokens[i]=wordsTokens[i].replace(str(unsortedIntegerNumbers.pop(0)), str(integerNumbers.pop(0)))
            if(len(unsortedIntegerNumbers)>0):
                index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
        
for word in wordsTokens:
    print(word,end=' ')




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