检查回文
我对Python还不熟悉。但我做了调试。但找不到错误。你知道吗
import string
def is_palindrome(str_1, lowest_index, highest_index):
punct = set(string.punctuation)
print(punct)
#remove punctuations
no_punct = ""
for char in str_1:
if char not in punct:
no_punct = no_punct + char
print(no_punct)
# rmv_whtspc = no_punct.rstrip()
rmv_whtspc = no_punct.replace(' ','')
print(rmv_whtspc)
str_2 = rmv_whtspc.lower()
print(str_2)
if lowest_index > highest_index:
return True
else:
if str_2[lowest_index] == str_2[highest_index]:
return is_palindrome(str_2, lowest_index+1, highest_index-1)
else:
return False
调用函数:
str_1 = "Madama I am adam"
lowest_index = 0
highest_index = len(str_1)-1
print(is_palindrome(str_1, lowest_index, highest_index))
输出:
{'{', '<', '_', '$', '"', ',', '&', '\\', ']', '`', '%', "'", '#', '*', '+', '>', '/', '?', '=', '^', ')', '[', '(',
'~', '!', '@', '|', '}', ':', '.', ';', '-'}
Madama I am adam
MadamaIamadam
madamaiamadam
Traceback (most recent call last):
File "recursion_5_2problem.py", line 27, in <module>
print(is_palindrome(str_1, lowest_index, highest_index))
File "recursion_5_2problem.py", line 19, in is_palindrome
if str_2[lowest_index] == str_2[highest_index]:
IndexError: string index out of range
在清理字符串(删除标点和空格)之前,您将获得最低和最高索引。因此,您正在尝试访问字符串中的一个字符,该字符现在可能超出了边界。 我建议在将字符串放入回文函数之前清理它,然后获得函数本身的最低和最高索引(aka)。删除所有标点和空格后)。你知道吗
只是伪代码,但我相信你明白了!你知道吗
希望有帮助!:)
你犯的错误在Andrew Grass's answer中有很好的描述。你知道吗
这里有一个建议,你可以让这一切变得更简单:
对于清理,可以使用^{} 和
str.translate
;然后将字符串的前半部分与后半部分进行比较(相反):你可以把它当作:
相关问题 更多 >
编程相关推荐