Recursion 在忽略特殊字符时检查是否为回文
我没有通过最后一个测试用例,那是一个带有空格和单引号的测试用例。 我使用了s.strip,但错误仍然存在 还有别的办法吗 多谢各位Recursion 在忽略特殊字符时检查是否为回文,recursion,python-3.x,Recursion,Python 3.x,我没有通过最后一个测试用例,那是一个带有空格和单引号的测试用例。 我使用了s.strip,但错误仍然存在 还有别的办法吗 多谢各位 from test import testEqual def removeWhite(s): s.strip() s.strip("'") return s def isPal(s): if s == "" or len(s) == 1: return True if removeWhite(s[0]) !
from test import testEqual
def removeWhite(s):
s.strip()
s.strip("'")
return s
def isPal(s):
if s == "" or len(s) == 1:
return True
if removeWhite(s[0]) != removeWhite(s[-1]):
return False
return isPal(removeWhite(s[1:-1]))
testEqual(isPal(removeWhite("x")),True)
testEqual(isPal(removeWhite("radar")),True)
testEqual(isPal(removeWhite("hello")),False)
testEqual(isPal(removeWhite("")),True)
testEqual(isPal(removeWhite("hannah")),True)
testEqual(isPal(removeWhite("madam i'm adam")),True)
首先,您的
removewite
函数不会返回所有空格,因为strip只从字符串的末尾和开头删除。见:
>>> " a ".strip()
'a'
>>> " a a ".strip()
'a a'
因此,我建议采用这种方法:
def removeWhite(s):
return ''.join(filter(lambda x: x not in " '", s))
请注意,我使用join是因为filter返回需要转换回字符串的迭代器
为了找到回文,我建议使用以下函数:
def isPal(s):
if len(s) <= 1: # Special case to prevent KeyError later
return True
stripped = removeWhite(s) # Strip off all whitespaces
first = stripped[:len(stripped) // 2] # First half of the string
if len(stripped) % 2: # Length of string is even?
second = stripped[len(stripped) // 2 + 1:] # Drop the middle character
else:
second = stripped[len(stripped) // 2:] # Else keep it
secondrev = ''.join(reversed(second)) # Reverse the second half
return first == secondrev # And return wether they're equal.
def isPal(s):
如属例外(s)