Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'list' object has no attribute 'copy' in leetcode editor, but in my PyCharm it's no error

Tags:

python

I'm using python to solve the 'Longest Common Prefix ' problem in leetcode. Here is my code:

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

I make some testing in my PyCharm ,it's ok. But when I ran it in leetcode It gave me :

Runtime Error Message: Line 52: AttributeError: 'list' object has no attribute 'clear' Last executed input: ["a","b"]

which line 52 is:

minList.clear()

I'm a rookie , Thank you for helping me!Thanks!

like image 672
Ezio Shiki Avatar asked Sep 14 '25 12:09

Ezio Shiki


1 Answers

The Python 3 list class has a clear() method, but the Python 2 list class does not. This is most likely the source of the problem. It seems that leetcode will run your script using Python 2, so you should develop it in Python 2 as well to avoid incompatibilities like this.

like image 193
jangler Avatar answered Sep 16 '25 02:09

jangler