Answer to Question #189033 in Python for J NAGAMANI

Question #189033

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




1
Expert's answer
2021-05-06T11:02:42-0400
def IsNum(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


s = input()
words = s.split()
numbers = []
for x in words:
    if IsNum(x):
        numbers.append(int(x))
if len(numbers) < 2:
    print(s)
numbers.sort(reverse=True)
result = ''
for x in words:
    if IsNum(x):
        result += str(numbers[0])
        numbers = numbers[1:]
    else:
        result += x
    result += ' '
print(result[:-1])

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

Ram
24.06.21, 12:48

It does not pass if string is "I am10 years old and i was 5years old"

Assignment Expert
11.05.21, 00:29

Dear Guna Venkata Satya Bhaskara Nikhil Patchipulusu, program works according to the requirements, all tests passed

Guna Venkata Satya Bhaskara Nikhil Patchipulusu
10.05.21, 15:32

this is not working for all test cases

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS