A hard-coded solution without lists:
def near_ten(num):
return ((num%10) <= 2) or ((num%10) >= 8)
A generalized version, as some commenters asked for:
def near_num(num,mult,diff):
return ((num%mult) <= diff) or ((num%mult) >= (mult-diff))
def near_ten(num):
return near_num(num,10,2)
The times I got for this were: (using existing answers to compare against)
>>> import timeit
>>> timeit.timeit('(128%10) in range(0,3) or (128%10) in range(8,10)')
0.5436179637908936
>>> timeit.timeit('(128%10) in [0,1,2,8,9]')
0.15247392654418945
>>> timeit.timeit('(128%10) <= 2) or ((128%10) >= (10-2))')
0.11723899841308594
So, it seems a little faster than even the hard-coded list.
I thought about adding a variable to store the value of (num%mult)
, but figure that a smart compiler should automatically put that in a temporary variable for reuse. So, I am curious as to opinions on how that would affect speed, memory, and (most importantly to me) readability.