2015-10-18 75 views
1

我想使用遞歸採取混合字符串並在整數上添加值。一個例子輸入是「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) 

我已經嘗試了很多不同的東西,但我似乎無法得到所期望的結果。

+0

請不要在你的代碼中使用== True。 – Brian

回答

2

如果rest是數字,則不需要關心;只需添加的first值(即0,如果不是一個數字),加上遞歸結果:

def toNumber(s): 
    if not s: 
     return 0 

    first = s[0] 
    value = int(first) if first.isdigit() else 0 
    return value + toNumber(s[1:]) 

其他說明:

  • 空字符串 'falsey';所以not s只有在字符串爲空時才爲真。因此可以將len(s) == 0簡化爲not s
  • 在布爾測試中沒有必要使用== True,這就是if已經爲您做的。

演示:

>>> def toNumber(s): 
...  if not s: 
...   return 0 
...  first = s[0] 
...  value = int(first) if first.isdigit() else 0 
...  return value + toNumber(s[1:]) 
... 
>>> toNumber('ab4h5h6') 
15 
+0

謝謝,那工作完美。我正在考慮這個問題。 – MDiG

0

你過於複雜的事情。遞歸應該總是返回當前字符的數量值加上函數的結果呼籲字符串的其餘部分:

def toNumber(s): 
    if len(s) == 0: 
     return 0 

    first = s[0] 
    rest = s[1:] 

    numFirst = 0 
    if first.isdigit(): 
     numFirst = int(first) 

    return num_first + toNumber(rest) 
1

非常最短:

toNumber = lambda s: bool(s) and ((s[0].isdigit() and int(s[0])) + toNumber(s[1:]))

如果您不需要遞歸:

toNumber = lambda s: sum(int(i) for i in s if i.isdigit())

甚至一個字符短,雖然萊小號Python的:

toNumber = lambda s: sum(map(int,filter(str.isdigit,s))))

+1

恕我直言,迄今爲止這裏最好的答案。順便說一句,使用'map'和'filter'不僅是Pythonic,它還是(在Python 2中)通過創建兩個不必要的列表來浪費內存。 – Pierre

+0

非常感謝!我應該更多地解釋我的代碼,但是我不喜歡,因爲它會迫使人們做一些研究:( 是的,允許體面的函數式編程實際上是Python 3的改進之一! – Labo

0

這裏是另一種解決方案。

策略:不顧一切地對待每一個數字作爲一個int和捕獲異常

def toNumber(s): 
    if len(s) == 0: 
     return 0 
    try: 
     return int(s[:1]) + toNumber(s[1:]) 
    except ValueError: 
     return toNumber(s[1:]) 

而這裏採用了同樣的策略非遞歸版本

def toNumberNonRecursive(s): 
    total = 0 
    for c in s: 
     try: 
      total += int(c) 
     except ValueError: 
      # not an int 
      pass 

    return total 

輸出:

>>> print(toNumber('1a2b3c')) 
6 
>>> print(toNumber('')) 
0 
>>> print(toNumber('abc')) 
0 
>>> print(toNumber('w48957jmc98(&H(*&398cmdi98')) 
87