Reputation: 93
Please is there a faster way to find out if a number is between two numbers. My current code is below. Thanks
lists = [2.3, 4, 3,5.5, 6.5, 7.5, 6, 8]
newlist = []
a = 2
b = 7
for i in lists:
if min(a, b) < i < max(a, b):
newlist.append(i)
print(newlist)
Upvotes: 0
Views: 1990
Reputation: 36370
When looking for where your code is slow, profile built-in module is handy. Here we can use it following way
import cProfile as profile
def func():
lists = [2.3, 4, 3,5.5, 6.5, 7.5, 6, 8]
newlist = []
a = 2
b = 7
for i in lists:
if min(a, b) < i < max(a, b):
newlist.append(i)
print(newlist)
profile.run('func()')
output is
[2.3, 4, 3, 5.5, 6.5, 6]
27 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <stdin>:1(func)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
8 0.000 0.000 0.000 0.000 {built-in method builtins.max}
8 0.000 0.000 0.000 0.000 {built-in method builtins.min}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
6 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
As you might deduce max
and min
was used 8 times each but in this case once for min
and once for max
would be enough. Sample data is too tiny to say anything useful about time of execution of components. If you wish you might use more data (longer lists
) and look for results.
Upvotes: 0
Reputation: 13929
Try the following:
a, b = min(a, b), max(a, b)
newlist = [x for x in lists if a < x < b]
With 100000 iterations, I found it 3 times faster than the original code. Using list comprehension instead of if
helps a little, but most improvements come from pre-defining max and min before list comprehension (or if
);
Upvotes: 2
Reputation: 255
lists = [2.3, 4, 3,5.5, 6.5, 7.5, 6, 8]
newlist = []
a = 2
b = 7
minimum = min(a, b)
maximum = max(a, b)
for i in lists:
if minimum < i < maximum:
newlist.append(i)
print(newlist)
This will make things faster as we are not computing minimum and maximum everytime when the loop runs and conditions are checked.
Upvotes: 2