【发布时间】:2016-08-04 19:16:00
【问题描述】:
假设变量x 和theta 可以分别取可能的值[0, 1, 2] 和[0, 1, 2, 3]。
假设在一个实现中,x = 1 和 theta = 3。表示这一点的自然方式是使用元组 (1,3)。但是,我想用单个索引标记状态 (1,3)。这样做的一种“蛮力”方法是形成所有可能的有序对(x,theta) 的笛卡尔积并进行查找:
import numpy as np
import itertools
N_x = 3
N_theta = 4
np.random.seed(seed = 1)
x = np.random.choice(range(N_x))
theta = np.random.choice(range(N_theta))
def get_box(x, N_x, theta, N_theta):
states = list(itertools.product(range(N_x),range(N_theta)))
inds = [i for i in range(len(states)) if states[i]==(x,theta)]
return inds[0]
print (x, theta)
box = get_box(x, N_x, theta, N_theta)
print box
这给出了(x, theta) = (1,3) 和box = 7,如果我们在states 列表中查找它是有意义的:
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
但是,这种“蛮力”方法似乎效率低下,因为应该可以预先确定索引而无需查找它。有什么通用的方法可以做到这一点吗? (N_x和N_theta的状态数在实际应用中可能会有所不同,笛卡尔积可能会有更多变量)。
【问题讨论】:
-
您可以使用哈希寻址,将两个组件取模一个大常数,然后在发生冲突时附加到每个哈希键后面的列表中。因此,例如 c2 * (x % c1) + (y % c2) 将是哈希键。
标签: python