I am trying to reverse a list via recursion
def my_rev1(data):
if len(data) == 0:
return []
else:
head = data[:-1]
tail = data[-1]
my_rev1(head).insert(0, tail) # does not work property
return head
def my_rev2(data):
if len(data) == 0:
return []
else:
head = data[:-1]
tail = data[-1]
return [tail] + my_rev2(head) # correct
print("my_rev1")
print(my_rev1([1]))
print(my_rev1([1, 2, 3]))
print("my_rev2")
print(my_rev2([1]))
print(my_rev2([1, 2, 3]))
The output is:
my_rev1
[]
[1, 2]
my_rev2
[1]
[3, 2, 1]
I wonder why the first recursive function is not correct? What is the difference between the 2 function?
This line here
my_rev1(head).insert(0, tail)
is the issue. The result from calling my_rev1 isn't being stored anywhere.
So you need something like this:
rev_head = my_rev1(head)
rev_head.insert(0, tail)
return rev_head
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With