0

I have no clue how to clearly simplify the requirements for the if statement to run. Is there a simpler way I could have done this? The code is supposed to return True if the number is 2 integers near 10, either being above or below.

def nearten(num):
    if (abs(num - 2) % 10) == 0 or (abs(num + 2) % 10) == 0 or (abs(num - 1) % 10) == 0 or (abs(num + 1) % 10) == 0 or num % 10 == 0:
        return True
    return False
benvc
  • 14,448
  • 4
  • 33
  • 54
  • 2
    `def nearten(num): return abs(10 - num) <= 2` – PMende Apr 09 '19 at 21:18
  • Like @PMende said: are you sure that is the condition for what you want? Because `x % 10` gets you last digits. eg `123 % 10 == 3` - which 123 is not near 10. – foobarna Apr 09 '19 at 21:21
  • @foobarna I'm going off of the supplied description of the question, which is "The code is supposed to return True if the number is *2 integers near 10*, either being above or below." If Curtis's code is closer to his desired behavior than mine, I can provide modifications. – PMende Apr 09 '19 at 21:27

1 Answers1

3

You're certainly over-complicating things. Here is a much more flexible version:

def near_ten(num, close=2):
    return abs(10 - num) <= close

An alternate version (if you're looking for numbers close to any multiple of 10):

def near_ten_multiple(num, close=2):
    return abs(10 - (num % 10)) <= close
PMende
  • 5,171
  • 2
  • 19
  • 26