I'm currently working on a project where a lot of different accounting is done and I came to see this pattern very often:
if A > X:
B += 1
else:
C += 1
I know ternary operator but if I understand it correctly the shortest way how to utilize it would be:
B += 1 if A > X else False
C += 1 if A <= X else False
since ternary operator is connected to the variable used in its head. So using ternary operator is obviously worse than the previous if/else both from computational and readability standpoint.
The other idea was to create a simple function like this:
conditional_bumper(positive_case_var, negative_case_var, condition_var, compare_to=0)
then the usage looks like:
conditional_bumper(B, C, A, X) # X being optional
so I can one line it every time I see it but at the same time this seems to me like a very 'hacky' solution. Is there a better way I don't see?
A > X. If this is a case, there is probably a way you can utilizecollections.CounterB += A > X; C += A <= X- your second code block is relying on the fact thatFalsehas a numeric value of 0, might as well rely onTruehaving a value of 1 as well.0 if A>X else 1is a bit counter-intuitive (especially if treating0as the "truthy" case) since booleans can be used as keys directly. See my answer