Answer to Question #204128 in Python for lakshmi

Question #204128

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

Note: There will not be any negative numbers or numbers with decimal part.


1
Expert's answer
2021-06-07T05:51:18-0400
import re
s = input('Enter string? ')
if re.findall(r'[\-][0-9]+', s) or re.findall(r'[0-9]+[\.]', s):
    print('Incorrect input in the line should not contain negative and fractional numbers')
else:
    numbers = re.findall(r'\d+', s)
    numbers_digit = [int(i) for i in numbers]
    numbers_digit.sort(reverse=True)
    result = s
    for i in numbers:
        result = result.replace(i,'-1' ,1)
    for i in numbers_digit:
        result = result.replace('-1',str(i) ,1)
    print(result)

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