我的教授要我创建一个函数,该函数返回字符串中的数字总和,但不使用任何列表或列表方法。
操作时,该函数应如下所示:
>>> sum_numbers('34 3 542 11')
590
通常,使用列表和列表方法时,会很容易创建这样的函数。但是尝试不使用它们便是一场噩梦。
我尝试了以下代码,但它们不起作用:
>>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
我没有得到1、2和3都转换成整数并加在一起,而是得到了字符串“ 11”。换句话说,字符串中的数字仍未转换为整数。
我也尝试使用一个map()
函数,但是得到了相同的结果:
>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
当然完全愚蠢,但是很有趣:
s = '34 3 542 11'
n = ""; total = 0
for c in s:
if c == " ":
total = total + int(n)
n = ""
else:
n = n + c
# add the last number
total = total + int(n)
print(total)
> 590
假设所有字符(除了空格)都是数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句