【发布时间】:2019-10-27 09:24:34
【问题描述】:
我正在编写一个动态编程函数,该函数在 Python 中找到最长的回文子串:
def longestPalindrome(s: str) -> str:
dict = {}
start = 0
end = 0
# initialize base cases and left of base cases
for i in range(len(s)):
dict[(i,i)] = 1
for y in range(len(s), -1, -1):
for x in range(y, len(s)):
print((x,y))
# memo check
if (x, y) not in dict.keys():
if s[x] == s[y]:
if x - y == 1:
dict[(x,y)] = 1
if (end - start) <= (x-y):
start = y
end = x
elif dict[(x-1,y+1)] == 1: # if substr betweet x & y is palindrome
dict[(x,y)] = 1
if (end - start) <= (x-y):
start = y
end = x
else: # ISSUE HERE
dict[(x,y)] = 0
return s[start:end+1]
在函数中输入“aaabaa”时出现以下错误: KeyError: (4, 1)
当我进行以下更改时,它会正确输出
def longestPalindrome(s: str) -> str:
dict = {}
start = 0
end = 0
# initialize base cases and left of base cases
for i in range(len(s)):
dict[(i,i)] = 1
for y in range(len(s), -1, -1):
for x in range(y, len(s)):
print((x,y))
# memo check
if (x, y) not in dict.keys():
dict[(x,y)] = 0 # **CHANGE**
if s[x] == s[y]:
if x - y == 1:
dict[(x,y)] = 1
if (end - start) <= (x-y):
start = y
end = x
elif dict[(x-1,y+1)] == 1: # if substr betweet x & y is palindrome
dict[(x,y)] = 1
if (end - start) <= (x-y):
start = y
end = x
# else: # **REMOVE**
# dict[(x,y)] = 0
return s[start:end+1]
我很确定这两个版本的函数在逻辑上是相同的,但我不知道为什么第一个不起作用。
【问题讨论】:
-
与该错误一起,您还会得到一个回溯,告诉您错误发生在哪一行。有很多地方使用 dict[tuple] ,所以不清楚它是哪个。养成包含完整错误消息的习惯,以最大限度地提高响应质量。
-
强烈建议不要使用名为
dict的变量,因为dict也是内置变量。
标签: python dynamic-programming