Why my function does not return the list?
Question:
The strangest thing is that I place a print()
just before the return
and the print does give the values I expect, but then I receive None
.
class listNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = listNode(1)
b = listNode(2)
c = listNode(4)
def convert_to_list_rec(nod, list=[]):
if nod == None:
print(list)
return list
list.append(nod.val)
convert_to_list_rec(nod.next, list)
arr = convert_to_list_rec(a)
Answers:
You need to return from the recursive call, see this example:
class listNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = listNode(1)
a.next = listNode(2)
a.next.next = listNode(4)
def convert_to_list_rec(nod, res):
if not nod:
return res
return convert_to_list_rec(nod.next, res + [nod.val])
arr = convert_to_list_rec(a, [])
print(arr)
Output:
[1, 2, 4]
The strangest thing is that I place a print()
just before the return
and the print does give the values I expect, but then I receive None
.
class listNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = listNode(1)
b = listNode(2)
c = listNode(4)
def convert_to_list_rec(nod, list=[]):
if nod == None:
print(list)
return list
list.append(nod.val)
convert_to_list_rec(nod.next, list)
arr = convert_to_list_rec(a)
You need to return from the recursive call, see this example:
class listNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = listNode(1)
a.next = listNode(2)
a.next.next = listNode(4)
def convert_to_list_rec(nod, res):
if not nod:
return res
return convert_to_list_rec(nod.next, res + [nod.val])
arr = convert_to_list_rec(a, [])
print(arr)
Output:
[1, 2, 4]