Answer to Question #195340 in Python for mohammad

Question #195340

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.


sample inputs1:

I am 5 years and 11 months old

sample output1:

I am 11 years and 5 months old

sample inputs2:

3times4 is12

sample output2:

12times4 is3

1
Expert's answer
2021-05-19T05:05:20-0400
def splitd(s):
    W = []
    N = []
    w = ''
    num = ''
    inNum = False
    for c in s:
        if c  in '1234567890':
            if inNum:
                num += c
            else:
                inNum = True
                num = c
                W.append(w)
                w = ''
        else:
            if inNum:
                N.append(num)
                inNum = False
                w = c
            else:
                w += c
    if inNum:
        N.append(num)
    W.append(w)
    return W, N


def swapNum(L, N):
    s = ''
    n = len(N)
    for i in range(n):
        s += L[i] + N[n-1-i]
    s += L[-1]
    return s


def main():
    s = input()
    W, N = splitd(s)
    s = swapNum(W, N)
    print(s)


main()

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

mohammad
19.05.21, 12:43

this code is not solving 23times89 62 98is88 and 32times4 is12

Mohammad
19.05.21, 12:30

Not passing 32times88 99is48

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS