2016-11-01 43 views
0

我得到了一些像(0,1),[1,2],...,[9,10)的區間。我想知道一個浮點值,e.g 3.75,屬於哪個區間。我做的是做左邊界清單[0,1,...,9]和右邊界清單[1,2,...,10]。然後找到3.75大於它的左邊界的第一個值,3。然後找到3.75小於它的右邊界的第一個值,4。然後3.75屬於區間[3,4]。是否有更好的如何找到3.75屬於哪個區間?Python:我如何獲得間隔屬於的浮點值?

回答

1

只存儲一個邊界列表就足夠了。您可以使用bisect_right找到區間的左邊界的索引,然後index + 1是正確的邊界:

import bisect 

def find(num, boundaries): 
    if boundaries[0] < num < boundaries[-1]: 
     index = bisect.bisect_right(boundaries, num) 
     return boundaries[index - 1], boundaries[index] 
    return None 

b = range(11) 
CASES = [3.75, 0, 10, 5, 0.1, 9.9, 11, -1, 6.7] 

for n in CASES: 
    print('{} belongs to group {}'.format(n, find(n, b))) 

輸出:

3.75 belongs to group (3, 4) 
0 belongs to group None 
10 belongs to group None 
5 belongs to group (5, 6) 
0.1 belongs to group (0, 1) 
9.9 belongs to group (9, 10) 
11 belongs to group None 
-1 belongs to group None 
6.7 belongs to group (6, 7) 
0

您也可以嘗試使用地板()和小區()在Python數學庫中運行,以解決您的問題。

import math 
lb = [0,1,2,3,4,5,6,7,8,9] 
ub = [1,2,3,4,5,6,7,8,9,10] 

inp = raw_input('Enter a number : ') 
num = float(inp) 

term = [[x, y] for x, y in zip(lb, ub) if int(math.floor(num)) == x and  int(math.ceil(num)) == y] 
if term == []: 
    print str(num) + ' does not belong to any specified interval' 
else: 
    print str(num) + ' belongs to the interval ' + str(term[0])