我有一个回文递归函数,它适用于除带空格的单词外的所有单词。如何修复代码以不考虑空格?
def ispalindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return ispalindrome(word[1:-1])
print(ispalindrome("taco cat"))
只需修改字符串,就可以去掉空白。一种方法是使用python的splitjoin函数,另一种方法则是使用regex。
这是一个运行代码的示例:
def ispalindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return ispalindrome(word[1:-1])
print(ispalindrome(''.join("taco cat".split())))
输出:真实
我希望这能有所帮助!
在函数中添加该行。这将删除空白和其他表格信息。
def ispalindrome(word):
word = word.strip() # remote white spaces and tabular information
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return ispalindrome(word[1:-1])
class Solution:
def recursive(self,s:str):
string=''.join(char.lower() for char in s if char.isalnum())
def dfs(s:str):
if len(s)<=1:
return True
if s[0]==s[-1]:
#reduce the bigger problem to smaller problem
return dfs(s[1:-1])
return dfs(string)
您应该删除函数开头字符串中的空格,因为空格也是一个字符,函数也会检查它。
def ispalindrome(word):
word = word.replace(' ', '')
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return ispalindrome(word[1:-1])
print(ispalindrome("taco cat"))
有不同的方法可以从字符串中删除空格,它们是:
1(
string = string.replace(" ", "")
2(
string = "".join(string.split())
3(
import re
pattern = re.compile(r's+')
string = re.sub(pattern, '', string)
4(
import string
string = string.translate(None, ' ntr')