Answer to Question #194552 in Python for sai

Question #194552

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.


1
Expert's answer
2021-05-18T02:58:09-0400
# 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])

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
APPROVED BY CLIENTS