1

Suppose that I have a numeric variable which will have another value added to it, but I want to make sure that this variable never exceeds a maximum value, and upon being exceeded, will simply default to the maximum value.

For example, given a maximum value of 100, and a function which does this which is called maxadd:

input1 = 90
input2 = 8
maxadd(input1, input2, 100)
>>> 98

input1 = 95
input2 = 8
maxadd(input1, input2, 100)
>>> 100

I could just define it as a normal function like this:

def maxadd(a, b, _max):
    res = a + b
    if res > _max:
        return _max
    return res

But I feel like it could be done in a single line, maybe with a lambda. I can't seem to figure anything out though. Performance is also a concern so I would like the fastest solution possible, and I feel like this function may be taking unnecessary steps

3 Answers 3

9

You can use min(a + b, max_value).

Sign up to request clarification or add additional context in comments.

Comments

6

Logically, you want to return either a + b or _max, whichever is smaller. So you can use the built-in function min for this:

def maxadd(a, b, _max):
    return min(a + b, _max)

Comments

2

If you want to use a lambda:

 f = lambda a, b, max_: min(a + b, max_)

For example:

f(90, 8, 100)

98

f(95, 8, 100)

100

2 Comments

How does using lambda (as opposed to def f(...) make a difference?
The difference is that using a lambda means the name f won't be included in the stack trace if it throws an exception (e.g. when calling f(1, 2, None)). That's undesirable, so generally if a function has a name then it shouldn't be a lambda.

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.