我想使用遞歸採取混合字符串並在整數上添加值。一個例子輸入是「ab4h5h6」和放出來會是15Python使用遞歸採取混合字符串,並將字符串中的整數加起來
這裏是我到目前爲止的代碼
def toNumber(s):
total = 0
if len(s) == 0:
return 0
else:
first = s[0]
rest = s[1:]
num_rest = toNumber(s[1:])
if first.isdigit()== True:
return int(first) + total
else:
if rest.isdigit()== True:
return int(rest) + int(num_rest)
我已經嘗試了很多不同的東西,但我似乎無法得到所期望的結果。
請不要在你的代碼中使用== True。 – Brian