需要一个程序的帮助,该程序旨在为回文中的一个键的单词返回要删除的键的索引(从前到后读取相同的空格,删除空格)。如果已经有回文或两个+键,则仅返回一个。该程序除“ reefer”之类的单词外,大多数情况下都可以正常运行。它没有返回要删除的第一个“ e”的索引,而是返回了“ f”的索引。这是因为检查反向后字母是否与正向相同的代码发现两个方向上都有一个“ e”,因此“ f”必定是错误的。必须有更好的方法来执行此操作,否则任何人都可以想到解决此问题的方法吗?
def near_palindrome(word):
string = list(word.replace(' ', ''))
is_pal = is_palindrome(string)
if is_pal == False:
result = []
for char in string:
rev_index = len(string) - string.index(char) - 1
if string[string.index(char)] != string[rev_index]:
if string[string.index(char) + 1] == string[rev_index]:
result.append(string.pop(string.index(char)))
elif string[string.index(char)] == string[rev_index - 1]:
result.append(string.pop(rev_index))
if len(result) == 1 and is_palindrome(string) == True:
for s in word:
if s == result[0]:
return word.index(s)
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
return word.index(s)
def is_palindrome(word): 如果单词==单词[::-1]: 返回True 其他: 返回False
以下代码:
代码
def is_palindrome(string, low, high):
" Check if substring from low to high is palindrome "
a = string[low:high+1]
b = a[::-1]
return a == b
def near_palindrome(string):
" Returns index of letter to remove to make palindrome None otherwise "
low = 0
high = len(string) - 1
# loop untill low and high cross each other
while low < high:
# If both characters are equal then
# move both pointer towards respecive ends
if string[low] == string[high]:
low += 1
high -= 1
else:
# Check if skipping str[low] makes the whole string a palindrome
if is_palindrome(string, low + 1, high):
return low
# Check if skipping str[high] makes the whole string a palindrome
if is_palindrome(string, low, high - 1):
return high
return None
# We reach here when complete string will be palindrome
# So not a near one
return None
Test
for s in ['reefer', "tanna", "atnna", "cilvic", "annas"]:
index = near_palindrome(s)
if index is not None:
print(f'string {s}, index {index}, key {s[index]}')
else:
print(f'string {s} is not a near palindrome')
输出
string reefer, index 2, key e
string tanna, index 0, key t
string atnna, index 1, key t
string cilvic, index 2, key l
string annas, index 4, key s
Performance
测试摘要
- 原始帖子:0.995秒
- 新代码:0.256秒
测试代码
def test_posted():
return [near_palindrome_posted(word) for word in lst]
def test_new():
return [near_palindrome(word) for word in lst]
from timeit import timeit
count = 10000
lst = ['reefer', "tanna", "atnna", "cilvic", "annas"]
print(timeit(test_posted, number=count))
print(timeit(test_new, number=count))