AttributeError:“list”对象在leetcode编辑器中没有属性“copy”,但在我的PyCharm中是n

2024-10-03 11:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python来解决leetcode中的“最长公共前缀”问题。这是我的代码:

class Solution:
# @param {string[]} strs
# @return {string}

def longestCommonPrefix(self, strs):


    if strs is None or strs == []:
        return ""


    if "" in strs:
        return ""



    minList=[]
    tempList=[]
    prefix=""



    if len(strs)>0:
        minLen = len(strs[0])
        for str in strs:
            if len(str)<minLen:
                minLen = len(str)

        for str in strs:
            if len(str)==minLen:
                minList.append(str)

    if len(minList)==1:
        prefix = minList[0]
    else:
        while True:
            isAllEqual = True

            for min in minList:
                if min!=minList[0]:
                    isAllEqual=False


            if isAllEqual:
                prefix=minList[0]
                break

            else:
                for min in minList:
                    tempList.append(min[:-1])

                minList.clear()
                minList=tempList.copy()
                tempList.clear()
    if prefix == "":
        return prefix


    for string in strs:

        if prefix in string:
            continue
        else:
            while prefix:


                prefix = prefix[:-1]

                if prefix =="":
                    return ""

                if prefix in string:

                    break

    return prefix

我用PyCharm做了些测试,没关系。 但当我在leetcode运行它时 它给了我:

运行时错误消息:第52行:AttributeError:“list”对象没有属性“clear” 上次执行的输入:[“a”,“b”]

第52行是:

^{pr2}$

我是新手,谢谢你的帮助!谢谢!在


Tags: inforstringprefixlenreturnifmin
2条回答

您正在使用python2解释器来运行这段代码,这是python3代码。有几种解决方法。 你可以使用一个shebang line

#!/usr/bin/python3

或者在终端中调用python3解释器。像

^{pr2}$

python3list类有一个clear()方法,但python2list类没有。这很可能是问题的根源。leetcode似乎将使用python2运行脚本,因此您应该在python2中开发它,以避免类似这样的不兼容。在

相关问题 更多 >