0

In my function, I only want to explicitly pass a single variable but It's being used twice. When I run the code, I get an error

def quickSort(arr, left=0, right=len(arr)-1):

NameError: name 'arr' is not defined

def quickSort(arr, left=0, right=len(arr)-1):
    # Base Case
    if left < right:
        pivotIdx = pivot(arr,left,right)
        # left side
        quickSort(arr, left, right=pivotIdx-1)
        # right side
        quickSort(arr, pivotIdx+1, right)
    return arr
arr = [4,8,2,1,5,7,6,3]
quickSort(arr)

How can i fix this?

Shadow Walker
  • 750
  • 1
  • 15
  • 34
  • There's nothing wrong in using one variable multiple times. You must've been given with the line of code where this error was thrown, what is it? Maybe in `pivot` function your array variable isn't called `arr` – Alexey Larionov Aug 19 '21 at 11:27
  • @AlexeyLarionov The line of code is ``def quickSort(arr, left=0, right=len(arr)-1):`` – Shadow Walker Aug 19 '21 at 11:28
  • 1
    Oh I see, you can't default your argument `right` with value `len(arr)-1` – Alexey Larionov Aug 19 '21 at 11:28
  • 1
    Because the value should be known without knowing any other argument (typically it should be some constant) – Alexey Larionov Aug 19 '21 at 11:29
  • @AlexeyLarionov Any work around without explicitly specifying value for **right**? – Shadow Walker Aug 19 '21 at 11:30
  • Please see the linked duplicate for the general technique. – Karl Knechtel Aug 19 '21 at 11:30
  • Some clunky workaround would be to default it to `-1`, and then in your function check if it's `-1` and reassign with `len(arr)-1` if so – Alexey Larionov Aug 19 '21 at 11:31
  • 1
    always put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot, not link to external portal). There are other useful information. – furas Aug 19 '21 at 12:15
  • 1
    you have to calculate it inside function - you could use `None` for this - `def quickSort(arr, left=0, right=None): if not right: right = len(arr)-1` – furas Aug 19 '21 at 12:17

0 Answers0