Reputation: 3626
I encountered this List Comprehension when looking for interesting ways to solve longest increasing subsequence problems:
def lis(a):
L = []
for (k,v) in enumerate(a):
L.append(max([L[i] for (i,n) in enumerate(a[:k]) if n<v] or [[]], key=len) + [v])
return max(L, key=len)
I've tried to understand it, but this is the best way I could understand it:
def lis(a):
L = []
for (k,v) in enumerate(a):
for (i,n) in enumerate(a[:k]):
if n < v:
L.append(max(L[i]) + [v])
else:
L.append([[]])
#L.append(max([L[i] for (i,n) in enumerate(a[:k]) if n<v] or [[]], key=len) + [v])
return max(L, key=len)
But this is incorrect... any help? Thank you.
Edit:
New code:
def lis(a):
L = []
for (k,v) in enumerate(a):
for (i,n) in enumerate(a[:k]):
if n < v:
L.append(max(L[i], key=len) + [v])
else:
L.append([[]] + [v])
When I run this on this list:
a = [5, 2, 1, 5, 3, 2, 10, 2, 4, 2, 1, 0, 5]
I get this error:
L.append(max(L[i], key=len) + [v])
TypeError: object of type 'int' has no len()
Upvotes: 2
Views: 77
Reputation: 62
You forgot + [v]
in the else statement.
Edit (think it's right):
def lis(a):
L = []
for (k, v) in enumerate(a):
tmp = []
for (i, n) in enumerate(a[:k]):
if n < v:
tmp.append(L[i])
if len(tmp) == 0:
tmp = [[]]
L.append(max(tmp, key=len) + [v])
return max(L, key=len)
Upvotes: 2