-1

Why I cant set array length as default argument in this case ?

def q_helper(arr, start=0, end=len(arr)-1):
    pivot = arr[start]
    swapIdx = start
    for i in range(len(arr)):
        if pivot > arr[i]:
            swapIdx += 1
            swap(arr, swapIdx, i)
        swap(arr, start, swapIdx)
    return swapIdx
Fahad17
  • 1
  • 1
  • 2
    Possible duplicate of [How to define default argument value based on previous arguments?](https://stackoverflow.com/questions/44025228/how-to-define-default-argument-value-based-on-previous-arguments) and [Is there a way to set a default parameter equal to another parameter value?](https://stackoverflow.com/questions/17157272/is-there-a-way-to-set-a-default-parameter-equal-to-another-parameter-value) – pault Jul 19 '19 at 15:16
  • As explained in the duplicates, you can't do this. In any case, `end` is not even used in your function anywhere. – pault Jul 19 '19 at 15:18

1 Answers1

-1

The short answer is: You can't set a default argument based on previous arguments because python needs to know the value when the function is defined (not when it's called).

A longer answer might be: If you're looking for a somewhat Pythonic way of doing what you want, I recommend setting the default value to None, and then setting the variable to whatever you want if it happens to be None. Something like this:

def q_helper(arr, start=0, end=None):
    if end is None:
        end = len(arr) - 1  # if not set, set it to one less than the array's length
J-L
  • 1,786
  • 10
  • 13