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.
# check if character is a number or not
def checkNum(str):
try:
int(str)
return True
except ValueError:
return False
# prompt user to enter the string input
userString = input("Enter the string: ")
words = userString.split()
nums = []
for i in words:
if checkNum(i):
nums.append(int(i))
if len(nums) < 2:
print(userString)
nums.sort(reverse = True)
newStr = ''
for i in words:
if checkNum(i):
newStr += str(nums[0])
nums = nums[1:]
else:
newStr += i
newStr += ' '
print(newStr[:-1])
Comments
Leave a comment