我试图在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
我讨厌成为那个人,但你为什么要递归呢?迭代字符也不是特别的pythonic。除非你以递归方式做这件事,否则我会建议使用phrase.replace(“”,“”) – DaveBensonPhillips
@ user3697163我把我的钱放在作业需求上。这是好的。但这可能是为什么。 – idjaw