-3

I'm using the abs built-in function to measure the difference between two numbers regardless of whether x is bigger than y or vice versa.

For example, if y = 5 and x = 7, the result will be 2. If y = 7 and x = 5, result will still be 2.

But if I want iterate until the result is 0, is there a way I can use abs or a different built-in so that y or x can be incremented or decremented so that the result will be 0?

I like the abs function, but it seems a shame to write code that has to check whether y is bigger than x or vice versa so as to increment or decrement until the difference is 0.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
SamChancer
  • 75
  • 5
  • 3
    What are you trying to achieve? Do you want to end up with `x = 6` and `y = 6`, or do you not care as long as both are equal? What have you tried - for example, why not pick one, increment it and then switch to decrementing if the difference gets larger? – jonrsharpe Mar 15 '16 at 14:13
  • `x, y = sorted([x, y])`, now always treat `x` as the smaller value...!? – deceze Mar 15 '16 at 14:14
  • Thanks, may try this. – SamChancer Mar 15 '16 at 16:00

2 Answers2

1

In case you really want to avoid conditional statements:

while abs(x-y) > 0:

    # do something

    sgn = (x-y)/abs(x-y)
    x += max(0, -sgn) - max(0, sgn)
Callidior
  • 2,899
  • 2
  • 18
  • 28
1
if x > y: x, y = y, x   # swap x and y if x > y
for x in range(x, y+1):
    diff = y-x

is pretty simple. Notice that one if-statement saves you N calls to abs (where N = abs(y-x)). So I think you should prefer the if-statement instead of trying to avoid it.


Since you didn't specify if you wished to increment (the smaller) or decrement (the larger) presumably by one, you might be only interested in the difference. In that case, you could use:

for diff range(abs(y-x), -1, -1):
    ...
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677