Asking about a general case, but specifically wanna know what Google thinks since it cares a lot about code readability and quality. I use Python for interviews, and sometimes when I face a problem that requires a recursion and where global variables (like `self.something` or using `nonlocal something`) can be handy, I do something like, ``` # for recursion using a helper function def function(a, b): __def callRecursion(c): # uses a and b ___... __callRecursion(...) ``` or ``` def function(a, b): __self.result = 0 __def callRecursion(c): # uses a and b ___... ___self.result += 1 __callRecursion(...) __return self.result ``` (using __ for indentation) I read that using global variables isn't really recommended, but it helps me code the solution pretty fast. For interviews (especially Google), are these formats (using global variable or nested helper) acceptable? Would love to hear from experienced interviewers. Thanks a lot #engineering #software #swe #interview #google
i personally always do the nested function route. this is what python is about, and when it comes to code quality, if you really think about it, that helper function is specifically for that parent function to solve its task. single responsibility. exposing it to the rest of the class almost seems like a code smell. so i will also go def solution(): def helper(): ... helper() route
Write only one-liners
Strong Nohire!
For interviews, I'll allow it. But please don't use self.x just so the variable is preserved for that one nested function in a production code. It pollutes the class. A nonlocal is definitely an improvement. Better yet is to keep the context in the recursive call, may be in the form of a collections.Counter passed as an arg in your example.
This has been my question since ages. Thanks for asking.