[英]Python: Simple If-Else statement not working
I'm coding a dynamic programming function that finds the longest substring that's a palindrome in Python:我正在编写一个动态编程 function,它找到了 Python 中最长的 substring 回文:
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]
I get the following error when inputting "aaabaa" into the function: KeyError: (4, 1)在 function 中输入“aaabaa”时出现以下错误:KeyError : (4, 1)
When I make the following changes, it outputs correctly当我进行以下更改时,它会正确输出
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]
I'm pretty sure the two versions of the functions are logically the same, but I cannot figure out why the first doesn't work.我很确定这两个版本的函数在逻辑上是相同的,但我无法弄清楚为什么第一个版本不起作用。
Did you intend to place the else
one tab width back?您是否打算将
else
one tab 宽度放回去? Your else
ought to be matching with the memoization step.你的
else
应该与记忆步骤相匹配。 It is matching with if s[x] == s[y]:
它与
if s[x] == s[y]:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.