2014-06-09 45 views
0

我寫過上面的程序。如果str中有chr,並且字符跟隨chr,則程序應該從str刪除chr,而不是chr。刪除字符串Python中的單個字符2.7

任何人都可以幫助我這是怎麼回事?爲什麼不按預期工作?我在函數內部看到函數調用的一些問題。

def removesingleton(str,chr): 
    ''' 
    (str,str)->(str) 
    Returns str with removed single chr 
    >>>removesingleton("Welcomee","e") 
    Wlcomee 
    >>>removesingleton("XabXXaX","X") 
    abXXa 
    ''' 
    output, index = "", 0 
    if str: 
     for char in str: 
      if char == chr: 
       if index+1 < len(str) and str[index+1] == chr: 
        output += str[:index+2] 
        removesingleton(str[index+2:],chr) 
       else: 
        removesingleton(str[index+1:],chr) 
      else: 
       output += str[index] 
       removesingleton(str[index+1:],chr) 
      index += 1 
    return output 

print removesingleton("XabXXaX","X") 
+1

我看到你打電話''removesingleton'裏面removesingleton'。但你對結果沒有做任何事情。你不應該把它分配到某個地方嗎? – Kevin

+1

您不應該使用'str'和'chr'作爲變量名稱 - 它們會影響內置插件 – jonrsharpe

+0

@Kevin我實際上使用它們來發送切片字符串以實現功能。所以我會添加我已經添加的字符輸出。我發現函數調用有問題。但我無法自己弄清楚。 – pythondetective

回答

1

你不需要任何遞歸調用。它們是完全不必要的,因爲你在單個調用中對整個字符串進行循環。 (你也忽略了返回值,所以在第一次遞歸時沒有太多意義。)

你需要做的是檢查下一個字符和上一個字符是否是當前字符的重複序列。你不需要做任何切片,也不需要明確的循環。下面的代碼的工作版本,蒸餾至單個發電機表達str.join調用內部:

def removesingleton(s, ch): 
    ''' 
    (str,str)->(str) 
    Returns a copy of s with all non-repeated instances of ch removed 
    >>>removesingleton("Welcomee","e") 
    Wlcomee 
    >>>removesingleton("XabXXaX","X") 
    abXXa 
    ''' 
    return "".join(c for i, c in enumerate(s)  # enumerate gives us our index 
        if c != ch or   # keep any of: non-matching characters 
         (i > 0 and s[i-1] == ch) or  # previous character was the same 
         (i < len(s)-1 and s[i+1] == ch)) # next character is the same 
+0

非常感謝你! – pythondetective