技术问询:为何此处arr未定义?无法将数组长度设为默认参数?
Hey there! Let's unpack your two questions about this Python code—they're both classic pitfalls with how Python handles function default arguments, so you're not alone here.
arr undefined in the default parameter? The key issue here is when Python evaluates default arguments: it calculates them at the time the function is defined, not when it's called.
When you write end=len(arr)-1 as a default parameter, Python tries to run len(arr) right when it parses the def q_helper(...) line. At that point, arr is just a parameter name—no actual array has been passed to the function yet. There's no variable named arr in scope here, so Python throws an undefined error.
This ties directly into the same evaluation timing problem. Even if arr did exist at function definition time (which it doesn't), using len(arr) as a default would only calculate that value once.
For example, if you first called q_helper([1,2,3]), the default end would be 2. But if you later called it with a longer array like q_helper([4,5,6,7]), the default end would still be 2 (from the first calculation), which is wrong. Default arguments are stored as part of the function object and don't update per call.
How to fix this
The standard workaround is to set the default parameter to a sentinel value (like None), then handle the default logic inside the function, where arr is guaranteed to be defined:
def q_helper(arr, start=0, end=None): # Set end to len(arr)-1 only if it wasn't provided if end is None: end = len(arr) - 1 pivot = arr[start] swapIdx = start # Quick note: your original loop uses range(len(arr)) which will iterate over the entire array # You probably want to loop from start+1 to end instead, to stay within the subarray: for i in range(start + 1, end + 1): if pivot > arr[i]: swapIdx += 1 swap(arr, swapIdx, i) swap(arr, start, swapIdx) return swapIdx
This way, every time you call the function without passing end, it calculates len(arr)-1 on the spot using the actual array you passed in—no undefined errors, and no stale default values.
内容的提问来源于stack exchange,提问作者Fahad17

