Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the insert method of list does not work correctly in my recursion?

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?

like image 939
enders_uu Avatar asked Jan 19 '26 04:01

enders_uu


1 Answers

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
like image 146
kimbo Avatar answered Jan 21 '26 19:01

kimbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!