2016-02-21 88 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