1

I have a function with three parameters, parameters two and three have default values. The default value for parameter three is dependent on the properties of parameter one. However, I obviously cannot perform any operations on parameter one in the 'def' line so I'm having trouble finding an efficient way of defining the default value of parameter three. What is the standard way to do this in python?

The following code is what I'm working with. Line one throws an error because I haven't really defined 'data' yet. What is the best workaround?

def stooge_sort(data, a = 0, b = len(data) - 1):
    if data[a] > data[b]:
        data[a], data[b] = data[b], data[a]
    if b + 1 - a >= 3:
        thirds = (b + 1 - a) / 3
        stooge_sort(data, a, b - thirds)
        stooge_sort(data, a + thirds, b)
        stooge_sort(data, a, b - thirds)
    return data

3 Answers 3

3

Remember that the default arguments are only evaluated once when the function object is created, so there's no way to put an expression like that in there. This is the same reason that people get surprised by the behaviour of default arguments that are assigned mutable values.

The usual way is to pick a default value that you know b will never be. None is most often a good choice.

def stooge_sort(data, a=0, b=None):
    if b is None:
        b = len(data) - 1
Sign up to request clarification or add additional context in comments.

Comments

2

Make the variable default to None, and then check if the variable is None, then if it is the case, change it to the value you wanted.

def stooge_sort(data, a = 0, b = None):
    if b is None:
        b = len(data) - 1
    if data[a] > data[b]:
        data[a], data[b] = data[b], data[a]
    if b + 1 - a >= 3:
        thirds = (b + 1 - a) / 3
        stooge_sort(data, a, b - thirds)
        stooge_sort(data, a + thirds, b)
        stooge_sort(data, a, b - thirds)
    return data

1 Comment

Use if b is None instead of ==. It can't hurt, and it's faster.
1

I believe the common workaround is to simply assign b some default value, for instance None, then adjust it based on data within the function:

def stooge_sort(data, a = 0, b = None):
    if b is None:
        b = len(data) - 1
    # continue doing work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.