python - 为何在这种情况下max()函数不能使用?
怪我咯
怪我咯 2017-04-18 09:22:28
0
2
1052
class LongestIncreasingSubsequence:
    def getLIS(self, A, n):
        # write code here
        dp=[0 for i in range(n)]
        dp[0]=1
        max=0
        print dp
        for i in range(n):
            now=0
            if i!=0:
                res=1
                for j in range(i):
                    if A[i]>A[j]:
                        res=dp[j]
                        now=now +1
                if now>=max:
                    max=now
                    dp[i]=res+1
                else:
                    dp[i]=res
        print dp
        #return max(dp)

kk=LongestIncreasingSubsequence()
kk.getLIS([1,4,2,5,3],5)

其中dp 是一个以int类型为成员的list
而使用max()函数时却会报错
TypeError: 'int' object is not callable
是由什么原因导致的?

怪我咯
怪我咯

走同样的路,发现不同的人生

Antworte allen(2)
PHPzhong

你的max函数在第五行被赋值成0了,max函数被覆盖了,你的变量改个名不要跟库函数重名了

伊谢尔伦

原因如同 @rayleisure 所說, 你在這裡使用 max 作為參考到 int 型態的 variable, 導致在

return max(dp)

時不但造成 build-in function 失效, 且會導致:

TypeError: 'int' object is not callable

這是因為你對整數 max, 進行了呼叫

總而言之, variable 的命名切記不要與:

  1. keywords

  2. build-in functions

  3. 標準庫或任何使用中的 package/module 的名稱

同名。

題外話

以下都是題外話

  1. 以你現在這段代碼來看, 似乎只需要寫一個 function 就好, 寫這個 class 看起來是多餘的 (除非你是在做線上題庫?)

  2. 不用特地傳 list 長度進去, Python 中問 list 長度可以很簡單地用 len()完成

  3. 對於 LIS 問題, 我簡化了一下你的 code:

只求 LIS 的長度:

def lislength(lst):
    """O(n^2) by button-up method"""
    n = len(lst)
    dp = [1 for x in lst]
    for i in range(n):
        for j in range(i+1, n):
            if lst[j] > lst[i]:
                dp[j] = max(dp[j], dp[i]+1)
    return max(dp)

整個 LIS 都要求出來:

def lis(lst):
    """O(n^2) by button-up method"""
    # use prev to record the previous elements
    n = len(lst)
    dp = [1 for x in lst]
    prev = [-1 for x in lst]
    for i in range(n):
        for j in range(i+1, n):
            if lst[j] > lst[i]:
                if dp[i]+1 > dp[j]:
                    prev[j] = i
                    dp[j] = dp[i]+1
    # find last elements of LIS
    maxl = maxpos = 0
    for pos, l in enumerate(dp):
        if l > maxl:
            maxl, maxpos = l, pos
    # trace back to find LIS
    seq = []
    while maxpos >= 0:
        seq.append(lst[maxpos])
        maxpos = prev[maxpos]
    seq.reverse()
    return seq

測試:

print(lislength([4,5,6,7,1,2,3,9]))
print(lis([4,5,6,7,1,2,3,9]))
print(lislength([1,3,6,7,4,5,9,10,15,12,14]))
print(lis([1,3,6,7,4,5,9,10,15,12,14]))

結果:

5
[4, 5, 6, 7, 9]
8
[1, 3, 6, 7, 9, 10, 12, 14]

我回答過的問題: Python-QA

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!