Subtract Unless Negative Then Return 0

帅比萌擦擦* 提交于 2021-02-18 08:53:42

问题


I'll preface with, this is solely to satisfy my curiosity rather than needing help on a coding project. But I was wanting to know if anyone knows of a function (particularly in python, but I'll accept a valid mathematical concept) kind of like absolute value, that given a number will return 0 if negative or return that number if positive.

Pseudo code:

def myFunc(x):
    if x > 0:
        return x
    else:
        return 0

Again, not asking the question out of complexity, just curiosity. I've needed it a couple times now, and was wondering if I really did need to write my own function or if one already existed. If there isn't a function to do this, is there a way to write this in one line using an expression doesn't evaluate twice.

i.e.

myVar = x-y if x-y>0 else 0

I'd be fine with a solution like that if x-y wasn't evaluated twice. So if anyone out there has any solution, I'd appreciate it.

Thanks


回答1:


One way...

>>> max(0, x)



回答2:


This should do it:

max(x-y, 0)



回答3:


Sounds like an analysis type question. numpy can come to the rescue!

If you have your data in an array:

x = np.arange(-5,11)
print x
[-5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10]

# Now do your subtraction and replacement.  
x[(x-y)>0] -= y
x[(x-y)<0]  = 0

If I understand your question correctly, you want to replace values in x where x-y<0 with zeros, otherwise replace with x-y.

NOTE, the solution above works well for subtracting an integer from an array, or operating on two array of equal dimensions. However, Daniel's solution is more elegant when working on two lists of equal length. It all depends on your needs (and whether you want to venture into the world of numpy or not).



来源:https://stackoverflow.com/questions/12728099/subtract-unless-negative-then-return-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!