Reputation: 173
I try to write a recursive function to return the longest increasing subsequence, but error occur says "TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
"
def helper(cur_seq, seq, cur_i, result):
if len(seq) == cur_i:
return result.append(cur_seq)
else:
next_i = cur_i + 1
if len(cur_seq) == 0 or seq[cur_i] > cur_seq[-1]:
temp = cur_seq.copy()
temp1 = cur_seq.copy()
temp.append(seq[cur_i])
return helper(temp, seq, next_i, result) + helper(temp1, seq, next_i, result)
else:
return helper(cur_seq.copy(), seq, next_i, result)
def longest_sub_sequence(seq):
cur_seq = []
result = helper(cur_seq, seq, 0, [])
max_length = 0
for i in result:
if len(i) > max_length:
max_length = len(i)
return max_length
if __name__ == "__main__":
seq = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
y = longest_sub_sequence(seq)
print(y)
Upvotes: 1
Views: 89
Reputation: 402483
list.append
is an in-place operation. For example,
l = [1, 2, 3]
result = l.append(4)
print(result)
# None
print(l)
# [1, 2, 3, 4]
append
returns None
, modifying l
in-place. This means that return result.append(cur_seq)
in your function will return None
, and the two recursive calls result in None + None
which gives you the TypeError
.
The fix would be to append first, return later.
def helper(cur_seq, seq, cur_i, result):
if len(seq) == cur_i:
result.append(cur_seq)
return result
...
Upvotes: 2