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.
The input will be a single line containing a string.
The output should be a single line containing the modified string with all the numbers in string re-ordered in decreasing order.
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
def IsNumber(word):
try:
int(word)
return True
except ValueError:
return False
def RearrangeNumbers(words):
source_words = words.split()
numbers = []
for w in source_words:
if IsNumber(w):
numbers.append(int(w))
if len(numbers) < 2:
return words
numbers.sort(reverse=True)
result_string = ''
for w in source_words:
if IsNumber(w):
result_string += str(numbers[0])
numbers = numbers[1:]
else:
result_string += w
result_string += ' '
return result_string[:-1]
print(RearrangeNumbers(input()))
Comments
Leave a comment