I am working on a function to print the list elements in reverse order using recursion. I came up with the following code
class Solution:
def __init__(self):
self.count=0
def reverseString(self, s):
def helper(s):
"""
Do not return anything, modify s in-place instead.
"""
print(s[:])
if len(s)>1:
s[0],s[len(s)-1]=s[len(s)-1],s[0]
print('s[0]',s[0])
print('s[len(s)-1]',s[len(s)-1])
helper(s[1:len(s)-1])
helper(s)
As you see, I am using print statements to debug the code. I get the following output
['h', 'e', 'l', 'p', 'o']
s[0] o
s[len(s)-1] h
['e', 'l', 'p']
s[0] p
s[len(s)-1] e
['l']
['o', 'e', 'l', 'p', 'h']
I see that my logic is working that there is something fundamental I am missing about variable update at local and global level. Can someone explain to me why I am swapping the first and last list element but my list output is not correct? I expect the output to be ['o', 'p', 'l', 'e', 'h'] On the other hand below modification seems to work fine
class Solution:
def __init__(self):
self.count=0
def reverseString(self, s):
def helper(left,right):
"""
Do not return anything, modify s in-place instead.
"""
print(s[:])
if left<right:
s[left],s[right]=s[right],s[left]
print('s[0]',s[left])
print('s[len(s)-1]',s[right])
helper(left+1,right-1)
helper(0,len(s)-1)
x=Solution()
s=["h","e","l","p","o"]
x.reverseString(s)
print(s)
['h', 'e', 'l', 'p', 'o']
s[0] o
s[len(s)-1] h
['o', 'e', 'l', 'p', 'h']
s[0] p
s[len(s)-1] e
['o', 'p', 'l', 'e', 'h']
['o', 'p', 'l', 'e', 'h']
I looked at the discussion Python inplace update of function arguments? and Immutable vs Mutable types which could possibly be related.