重新排列字符串中的数字
给定一个字符串,编写一个程序,以降序重新排列出现在字符串中的所有数字。注意:不会有任何负数或带小数部分的数字。
输入
输入将是包含字符串的单行。
输出
输出应该是一行,其中包含修改后的字符串,字符串中的所有数字都按降序重新排序。
解释:
例如,如果给定的字符串是“我 5 岁零 11 个月大”,则数字是 5、11。在将数字重新排序为“我 11 岁零 5 个月大”后,您的代码应该打印句子。
#Sample Input:
I am 5 years and 11 months old
#Sample Output:
I am 11 years and 5 months old
#Sample input:
I am 28 years 9 months 11 weeks and 55 days old
#Sample output:
I am 55 years 28 months 11 weeks and 9 days old
我的做法:
def RearrangeNumbers(source):
tmp0 = list(source)
tmp1 = [c if c.isdigit() else ' ' for.
c in tmp0 ]
tmp2 = "".join(tmp1)
tmp3 = tmp2.split()
numbers = []
for w in tmp3:
numbers.append(int(w))
if len(numbers) < 2:
return source
numbers.sort(reverse=True)
result_string = ''
i = 0
while i < len(source):
c = source[i]
if not c.isdigit():
result_string += c
else:
result_string += str(numbers[0])
numbers = numbers[1:]
i+=1
i+=1
return result_string
print(RearrangeNumbers(input()))
输出:
I am 55 years 28months 11 weeks and 9 days old
但是28个月之间应该有空间
您在代码中逐个字符地执行大量字符串操作。以数字方式查找数字是完成您必须做的事情的复杂方法。您丢失的空间是由您的方法造成的:
提示:检查文本中数字的长度——你可能并不总是用另一个 1 位数字替换 1 位数字——有时你需要用 3 位数字替换 1 位数字:
"Try 1 or 423 or 849 things."
在这种情况下,您的“逐个字符”替换会变得不稳定,并且您会失去空间。
本质上,你用"2 "
一个 2 位数字(或"12 "
一个 3 位数字等等)来替换空格。
最好是
string.formt()
以正确的顺序替换数字像这样:
def sortNumbers(text):
# replace all non-digit characters by space, split result
numbers = ''.join(t if t.isdigit() else ' ' for t in text).split()
# order descending by integer value
numbers.sort(key=lambda x:-int(x))
# replace all found numbers - do not mess with the original string with
# respect to splitting, spaces or anything else - multiple spaces
# might get reduced to 1 space if you "split()" it.
for n in numbers:
text = text.replace(n, "{}")
return text.format(*numbers) # put the sorted numbers back into the string
for text in ["I am 5 years and 11 months old",
"I am 28 years 9 months 11 weeks and 55 days old",
"What is 5 less then 45?",
"At 49th Street it is 500.", "It is $23 and 45."]:
print(sortNumbers(text))
输出:
I am 11 years and 5 months old
I am 55 years 28 months 11 weeks and 9 days old
What is 45 less then 5?
At 500th Street it is 49.
It is $45 and 23.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句