I thought MrSmith42's answers were really compact and readable. But I wanted to see if they were faster.
Also, I wanted to test numpy for comparison. Here's my numpy version:
def near_ten5(num_list):
a = np.mod(num_list, 10)
return np.logical_or(2 >= a, 8 <= a)
All the versions presented so far:
def near_ten1(num):
a = num % 10
if (10 - (10-a)) <= 2 or (10 - a) <= 2:
return True
else:
return False
def near_ten2(num):
a = num % 10
return 8 <= a or 2 >= a
def near_ten3(num):
return not(2 < (num % 10) < 8)
def near_ten4(num):
return abs(5 - num % 10) >= 3
def near_ten5(num_list):
a = np.mod(num_list, 10)
return np.logical_or(2 >= a, 8 <= a)
Code to test them for accuracy and speed:
from random import randint, random
import timeit
import numpy as np
accuracy_test = [-3.4, -2, 0.1, 22, 23]
for f in [near_ten1, near_ten2, near_ten3, near_ten4, near_ten5]:
print [f(x) for x in accuracy_test]
timer_test = [random()*randint(0, 20) for _ in xrange(10**5)]
%timeit [near_ten1(n) for n in timer_test]
%timeit [near_ten2(n) for n in timer_test]
%timeit [near_ten3(n) for n in timer_test]
%timeit [near_ten4(n) for n in timer_test]
%timeit near_ten5(timer_test)
Output:
[False, True, True, True, False]
[False, True, True, True, False]
[False, True, True, True, False]
[False, True, True, True, False]
[False, True, True, True, False]
10 loops, best of 3: 36.5 ms per loop
10 loops, best of 3: 26.5 ms per loop
10 loops, best of 3: 25.2 ms per loop
10 loops, best of 3: 28.1 ms per loop
100 loops, best of 3: 3.85 ms per loop
Unsurprisingly, the numpy
solution is the fastest, but is admittedly less elegant than what I call near_ten3()
, which is the answer from MrSmith42 / mkrieger1.
A couple of other minor comments:
- Docstrings would be good!
- All the current functions will fail if complex numbers are provided (and obviously also if non-numbers are provided).