Reputation: 1825
A = 200
B = -140
C = 400
D = -260
if A < 0:
v1 = 0
else:
v1 = A
if B < 0:
v2 = 0
else:
v2 = B
if C < 0:
v3 = 0
else:
v3 = C
if D < 0:
v4 = 0
else:
v4 = C
What is the shorthand implementation for the above code structure.? Is there a better / elegant / convenient way to do this?
Upvotes: 4
Views: 7016
Reputation: 35522
As an alternative to mgilson's excellent answer, you could subclass int
into a custom class to achieve this
>>> class V(int):
... def __new__(cls,val,**kwargs):
... return super(V,cls).__new__(cls,max(val,0))
Then use it directly:
>>> A=V(200)
200
>>> B=V(-140)
0
>>> [V(i) for i in [200, -140, 400, -260]]
[200, 0, 400, 0]
>>> A,B,C,D = [V(i) for i in [200, -140, 400, -260]]
The only advantage to do it this way is you can then override __sub__
and __add__
__mul__
appropriately and then you V ints will always greater than 0 even if you have a=V(50)-100
Example:
>>> class V(int):
... def __new__(cls,val,**kwargs):
... return super(V,cls).__new__(cls,max(val,0))
... def __sub__(self,other):
... if int.__sub__(self,other)<0:
... return 0
... else:
... return int.__sub__(self,other)
>>> a=V(50)
>>> b=V(100)
>>> a-b #ordinarily 50-100 would be -50, no?
0
Upvotes: 0
Reputation: 309831
A = 200
B = -140
C = 400
D = -260
v1, v2, v3, v4 = [x if x > 0 else 0 for x in (A, B, C, D)]
If you prefer to use the max
function to the python ternary operator, it would look like:
v1, v2, v3, v4 = [max(x, 0) for x in (A, B, C, D)]
However, if you're planning on having all of these variables treated the same, you might want to consider putting them in a list/tuple in the first place.
values = [200, -140, 400, -260]
values = [max(x, 0) for x in values]
Upvotes: 13
Reputation: 375405
This can be solved easily by using the max()
builtin and unpacking a list comprehension.
v1, v2, v3, v4 = [max(x, 0) for x in [a, b, c, d]]
An alternative solution is to use the map()
function - this is, however, less readable:
v1, v2, v3, v4 = map(lambda x: max(x,0), [a, b, c, d])
Upvotes: 4