Answer to Question #204642 in Python for Narendra

Question #204642

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.


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])

but if we are giving "Narendra52 is 12 years and 5 months old" 52 also should be calculated as a separate number but it is not acting like that
1
Expert's answer
2021-06-08T23:48:08-0400
def rearrangeNo(sentence):
    temp0 = list(sentence)
    temp1 = [c if c.isdigit() else ' ' for c in temp0 ]
    temp2 = "".join(temp1)
    temp3 = temp2.split()
    numbers = []
    for w in temp3:
        numbers.append(int(w))
    if len(numbers) < 2:
        return sentence
    numbers.sort(reverse=True)
    result_string = ''
    i = 0
    while i < len(sentence): 
        c = sentence[i]
        if not c.isdigit():
            result_string += c
        else:
            result_string += str(numbers[0])
            numbers = numbers[1:]
            while sentence[i].isdigit():
                i+=1
            result_string += sentence[i]
        i+=1
    return result_string


print(rearrangeNo(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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS