2016-02-21 87 views
0

我試圖在python中遞歸地刪除空格。我開始使用空字符串的基本情況返回self.phrase,假設它將返回None。我錯了嗎?下面的代碼:在Python中遞歸地刪除空格

class palindrome: 

    phrase = "" 

    def remove_spaces (self, phrase): 
     if self.phrase == "": 
      return self.phrase 
     if self.phrase[0] != " ": 
      return self.phrase[0] + remove_spaces (self.phrase[1:]) 

然而,單元測試失敗:

class test_remove_spaces(unittest.TestCase): 
    def test_remove_spaces_none(self): 
     self.assertEquals (remove_spaces (None), None) 

從測試的問題不能因一個錯誤。不完全確定爲什麼remove_spaces不可訪問。它是一個嵌套的問題,因爲我試圖讓隱藏在數據?:

Error 
Traceback (most recent call last): 
    File "C:\Users\******\Dropbox\CS2\CS2_Assignment2\Assignment2.py", line 24, in test_remove_spaces_none 
    self.assertEquals(remove_spaces(None), None) 
NameError: global name 'remove_spaces' is not defined 
+3

我討厭成爲那個人,但你爲什麼要遞歸呢?迭代字符也不是特別的pythonic。除非你以遞歸方式做這件事,否則我會建議使用phrase.replace(「」,「」) – DaveBensonPhillips

+0

@ user3697163我把我的錢放在作業需求上。這是好的。但這可能是爲什麼。 – idjaw

回答

1

remove_spaces是你palindrome類中的方法。您需要先實例化您的班級,然後才能撥打remove_spaces

class test_remove_spaces(unittest.TestCase): 
    def test_remove_spaces_none(self): 
     obj = palindrome() 
     self.assertEquals (obj.remove_spaces(None), None) 

此外,我建議通過PEP8 style-guide閱讀。類通常遵循駱駝的情況下,第一個字母大寫是,讓你的類可以被重命名爲:

class Palindrome: 
-1

你爲什麼不只是使用正則表達式?

import re 
subject = " test " 
no_space = re.sub(r"\s+", "", subject, 0, re.IGNORECASE) 
+3

正則表達式對於這個問題似乎有點重量級。我建議使用str.replace方法,正如我在原始帖子中提到的那樣 – DaveBensonPhillips