last day (15 days later) » 

10:11 PM
1
A: Alternative to global variable

DarrylGExample of using a mutable argument to get rid of globals def reverse(n, res_base = None): if res_base is None: res_base = [0, 1] # Use two element list for res, base # res_base[0] -> res # res_base[1] -> base i...

 
@F.V.--updated solution with an answer to your question as an alternative.
 
Thank you for that! For me, it is quite confusing that the first function does not assing res_base to the function, but res and base res, base = helper(n//10, res,base do. In other words, why and how does res_base get updated?
 
@F.V.--in the conditional there are two assignments to res_base, namely:: res_base[0] = (res_base[0] + (n%10)*res_base[1] and res_base[1] = res_base[1] * 10.
 
yea, sorry my question was poorly worded. Why would helper(n // 10, res, base) res = res + (n % 10) * base) base = base * 10 not work in the second code? This seems analogous to the first code
 
@F.V.--seems you're wondering why I need res, base =helper(n // 10, res, base), rather than just helper(n // 10, res, base). Is that right? The issue is res & base are local variables within the helper function. Meaning each time helper is called a new stack frame is created with it's local variables. Thus, the parent res, base are in a different stack frame from it's children. So when the children modify res, base it does not affect the res, base in the parent. Returning res, base to the parent allows the parent to update it's res, base.
 
10:11 PM
I see, weill explained! But in the def reverse(n, res_base = None) function, res_base is called with each function aswell, but apparently there, a new frame is not created. Is that because the variables is in the parent's frame anyway?
thanks for taking your time :D
 
@F.V.--I added yet another solution to show you how to do it without a return. Actually, a stack frame is created in both cases. The key difference is in the use of mutable vs. immutable arguments. If the argument is mutable then parents will see changes made by the children, otherwise they won't. Since numbers are immutable in Python, we have to send back the updated numbers for the parents to see changes. Lists are mutable, so the parents will see changes in the list.
 
ahh and the other one is a list, that it is why its mutable
and hence, it can be updated without sending back the new values
that explains a lot, thanks!
 
@F.V. --correct. It has to do with what it means for variables to be reassigned in Python vs. other languages. Meaning x = 4; x = 5 means something subtly different in Python vs. languages like C.
 
i see
is that an advantage or disadvantage for python
 
10:29 PM
A disadvantage for speed. An advantage for flexibility.
 
I see; I have to go to bed; Thanks again for your help, I can now sleep in peace :D I hope you are having a great day!
 
You too
 

last day (15 days later) »