Heim > Fragen und Antworten > Hauptteil
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
是由什么原因导致的?
伊谢尔伦2017-04-18 09:24:28
原因如同 @rayleisure 所說, 你在這裡使用 max
作為參考到 int
型態的 variable, 導致在
return max(dp)
時不但造成 build-in function 失效, 且會導致:
TypeError: 'int' object is not callable
這是因為你對整數 max
, 進行了呼叫
總而言之, variable 的命名切記不要與:
keywords
build-in functions
標準庫或任何使用中的 package/module 的名稱
同名。
以下都是題外話
以你現在這段代碼來看, 似乎只需要寫一個 function 就好, 寫這個 class 看起來是多餘的 (除非你是在做線上題庫?)
不用特地傳 list 長度進去, Python 中問 list 長度可以很簡單地用 len()
完成
對於 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