Check Which Range A Number Is Within
Solution 1:
Use bisect:
import bisect
ranges = [-64, -32, -16, -8, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 8, 16, 32, 64]
print(bisect.bisect(ranges, -65))
# 0print(bisect.bisect(ranges, -64))
# 1print(bisect.bisect(ranges, 63))
#16print(bisect.bisect(ranges, 64))
# 17bisect.bisect(l, value) returns the index at which value would have to be inserted in l, such that all values to the left are less than value. It will also be fast to search a large list, as it uses a bisection algorithm.
Solution 2:
Based off the way you described you could do something like this:
ranges = [-64, -32, -16, -8, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 8, 16, 32, 64]
defbuild_ranges(power):
ranges = [-0.5, 0, 0.5]
for i inrange(power):
ranges.append(2**i)
ranges.append(-2**i)
returnsorted(ranges)
deffind_which_range(value, ranges):
for i, rangeinenumerate(sorted(ranges)):
if value < range:
return i
returnNone
output = find_which_range(value, ranges)
Solution 3:
Mathew provided a looping solution that works fine. But also observe that you are checking basically, which powers of 2 your number is between. Thus, you can take the log.
import math
a_value = abs(value)
sign = 1if value > 0else-1
lg_value = math.log2(a_value)
range_ = (2**(sign*math.floor(lg_value)), 2**(sign*math.ceil(lg_value)))
note that slight modifications are required for ranges < 1.
Solution 4:
People already provided much shorter (and efficient) solutions. I am just posting here my attempt just to show one more way and logic to approach the problem using list comprehension.
deffind_which_range(value, ranges):
if value <= min(ranges):
c = 0elif value >= max(ranges):
c = len(ranges)
else:
c = [i+1for i inrange(len(ranges)-1) if ranges[i] <= value <= ranges[i+1]][0]
return c
value = -9
i = find_which_range(value, ranges)
Solution 5:
To find the right range, you can iterate over each range using zip function, like this:
ranges = [-64, -32, -16, -8, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 8, 16, 32, 64]
i = 9for p, n inzip(ranges[:-1], ranges[1:]):
if p <= i < n:
r = p, n
breakelse:
raise ValueError(i)
print(r)
You get: (8, 16)
Then you can use a mapping between each range and target values, something like this:
mapping = {
(-64, -32): 1,
(-32, -16): 2,
(-16, -8): 3
}
print(mapping[(-32, -16)])
2
Post a Comment for "Check Which Range A Number Is Within"