Answer to Question #188632 in Python for phani

Question #188632
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-04T13:07:25-0400
def RearrangeNumbers(source):
    tmp0 = list(source)
    tmp1 = [c if c.isdigit() else ' ' for c in tmp0 ]
    tmp2 = "".join(tmp1)
    tmp3 = tmp2.split()
    numbers = []
    for w in tmp3:
        numbers.append(int(w))
    if len(numbers) < 2:
        return source
    numbers.sort(reverse=True)
    result_string = ''
    i = 0
    while i < len(source): 
        c = source[i]
        if not c.isdigit():
            result_string += c
        else:
            result_string += str(numbers[0])
            numbers = numbers[1:]
            while source[i].isdigit():
                i+=1
            result_string += source[i]
        i+=1
    return result_string

print(RearrangeNumbers(input()))

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

chinna
19.05.21, 13:41

this is working for this "Exam23 is Not EndBy35 tomorrow98" and I "I am 5 years and 11 months old" but it is also working for this kind of "I am -5 years and 11.0 old" when the user give as an input which containing negative or decimal then also it is accepting not accpect the decimals or negatives.

santhosh
17.05.21, 12:48

code will not satisfy , if the given string contains numbers inbetween the alphabets. For example "Exam23 is Not EndBy35 tomorrow98"

chinna
17.05.21, 10:45

This code is not satisfying these conditions so you check it once, please *Note: There will not be any negative numbers or numbers with decimal part.

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS