[英]Python: Simple If-Else statement not working
我正在編寫一個動態編程 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]
在 function 中輸入“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]
我很確定這兩個版本的函數在邏輯上是相同的,但我無法弄清楚為什么第一個版本不起作用。
您是否打算將else
one tab 寬度放回去? 你的else
應該與記憶步驟相匹配。 它與if s[x] == s[y]:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.