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.
def IsNum(s):
try:
int(s)
return True
except ValueError:
return False
s = input()
words = s.split()
numbers = []
for x in words:
if IsNum(x):
numbers.append(int(x))
if len(numbers) < 2:
print(s)
numbers.sort(reverse=True)
result = ''
for x in words:
if IsNum(x):
result += str(numbers[0])
numbers = numbers[1:]
else:
result += x
result += ' '
print(result[:-1])
but if we are giving "Narendra52 is 12 years and 5 months old" 52 also should be calculated as a separate number but it is not acting like that
def rearrangeNo(sentence):
temp0 = list(sentence)
temp1 = [c if c.isdigit() else ' ' for c in temp0 ]
temp2 = "".join(temp1)
temp3 = temp2.split()
numbers = []
for w in temp3:
numbers.append(int(w))
if len(numbers) < 2:
return sentence
numbers.sort(reverse=True)
result_string = ''
i = 0
while i < len(sentence):
c = sentence[i]
if not c.isdigit():
result_string += c
else:
result_string += str(numbers[0])
numbers = numbers[1:]
while sentence[i].isdigit():
i+=1
result_string += sentence[i]
i+=1
return result_string
print(rearrangeNo(input()))
Comments
Leave a comment