Answer to Question #259411 in Python for masthan

Question #259411

rearrange numbers in a string




given a string write a program to arrange all numbers appearing in the string in decreasing order

1
Expert's answer
2021-10-31T12:14:23-0400
line = input()

words = []
numbers = []

word = ''
number = None
munus = False

for ch in line:
    if ch.isdigit():
        if number is None:
            number = int(ch)
            if minus:
                word = word[:-1]
            words.append(word)
            word = ''
        else:
            number = number*10 + int(ch)
    else:
        if word == '':
            word = ch
            if number is not None:
                if minus:
                    minus = False
                    number *= -1
                numbers.append(number)
            number = None
        else:
            word += ch
            if ch == '-':
                minus = True
            else:
                minus = False
if number is not None:
    numbers.append(number)
else:
    words.append(word)

numbers.sort(reverse=True)

line = ''
for i in range(len(numbers)):
    line += words[i] + str(numbers[i])
if len(words) > len(numbers):
    line += words[-1]

print(line)

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