【问题标题】:Python: Simple If-Else statement not workingPython:简单的 If-Else 语句不起作用
【发布时间】: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


【解决方案1】:

您是否打算将else 放回一个制表符宽度?您的else 应该与记忆步骤相匹配。它与if s[x] == s[y]:匹配

【讨论】:

  • 这个问题让我想说,不要将这么多 python 块放在一起,因为 python 让一个结束另一个开始的地方真的很混乱。使用函数封装代码块来缓解这一挑战。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 2023-03-13
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多