How does “if n is within 10 of either 100 or 200” correlate with using the absolute value function?
I get what absolute value is, but wouldn’t there be an easier/cleaner way without using abs()?
Thanks
Advertisement
Answer
Sure: you absolutely could (and I’d say should) write that like:
def almost_there(n): return 90 <= n <= 110 or 190 <= n <= 210
which I think more clearly communicates your intent to the next person who touches the code. However, I think your teacher wanted you to be aware of the “idiom” of abs(x - y) <= z
for “x is within z of y”, because this won’t be the last time you ever see it, either in software or in math. In fact, you’ll see |x-y|<z
in math a lot in certain subjects; for example, here’s an article on epsilon-delta proofs.
I think the code I wrote is more Pythonic. That said, you need to look at the code your teacher described and be able to instantly recognize it as the same thing as |x-y|<z
, no matter which way it’s written.