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
Sample Input
I am 2 years and 3 months old. This sentence4 5should be 6rearr7anged8. If possible -9these negative-12 nums
Sample Output
I am 12 years and 9 months old. This sentence8 7should be 6rearr5anged4. If possible 3these negative2 nums
import re
message = input()
message=message.replace('-', '')
wordsTokens= message.split()
integerNumbers=[int(num) for num in re.findall(r'\d+', message)]
unsortedIntegerNumbers=[int(num) for num in re.findall(r'\d+', message)]
integerNumbers.sort(reverse=True)
for i in range(0,len(wordsTokens)):
if(len(unsortedIntegerNumbers)>0):
index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
previousIndex=-2
while (len(unsortedIntegerNumbers)>0) and index!=-1 and index!=previousIndex:
previousIndex=index
index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
wordsTokens[i]=wordsTokens[i].replace(str(unsortedIntegerNumbers.pop(0)), str(integerNumbers.pop(0)))
if(len(unsortedIntegerNumbers)>0):
index=(wordsTokens[i].find(str(unsortedIntegerNumbers[0])))
for word in wordsTokens:
print(word,end=' ')
Comments
Leave a comment