2

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!

Ezio Shiki
  • 745
  • 6
  • 23
  • possible duplicate of [Why is there no list.clear() method in python?](http://stackoverflow.com/questions/1401933/why-is-there-no-list-clear-method-in-python) – awesoon Jun 07 '15 at 06:44

2 Answers2

3

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.

jangler
  • 949
  • 6
  • 7
1

You are using python2 interpreter to run this code which is python 3 code. There are several solution for this. You can use a shebang line like,

#!/usr/bin/python3

Or invoke the python3 interpreter in the terminal. like

$ python3 myscript.py
Community
  • 1
  • 1
salmanwahed
  • 9,450
  • 7
  • 32
  • 55