我有一个函数,它计算许多输入数组的笛卡儿积的第n个元素:
def prod(arrs, n):
out = []
for i,arr in enumerate(arrs):
denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
idx = n // denom % len(arr)
out.append( arr[idx] )
return out
这一职能发挥了巨大的作用:
a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]
for n in range(20, 30):
i = prod([a, b, c], n)
print(i)
1000,3.0,-21000,3.0,01000,3.0,21000,3.5,-11000,3.5,1,1,1
现在我需要“倒退”。
也就是说,给定输入数组[ a, b, c ]
和一个置换,在笛卡儿乘积中找出那个置换是哪个元素。(可以假定每个数组只包含不同的元素。)
例:
def n_from_prod(arrs, arr):
# TODO: calculate n
n = n_from_prod([a, b, c], [1000, 3.5, -2])
assert n == 25
问题:
给定多个输入数组的笛卡儿乘积的单个排列,我如何才能找到n,在这个序列中的哪个数,这个置换是?
发布于 2020-02-17 18:25:04
假设a,b,c
已排序,否则您必须使用index
或类似的:
def get_idx(x,a,b,c):
return np.ravel_multi_index([np.searchsorted(A,B) for B,A in zip(x,(a,b,c))],[*map(len,(a,b,c))])
测试:
import itertools as it
[get_idx(p,a,b,c) for p in it.product(a,b,c)]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149]
发布于 2020-02-17 14:08:20
我已经设法把这篇文章写在这里,以防将来有人对我有用。
def n_from_prod(arrs, arr):
assert len(arrs) == len(arr)
n = 0
for i in range(len(arr)):
idx = arrs[i].index(arr[i])
mult = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
n += idx * mult
return n
测试:
a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]
for n in range(20, 30):
i = prod([a, b, c], n)
n_calc = n_from_prod([a, b, c], i)
assert n == n_calc
print(n, n_calc, i)
输出:
20 20 000、3.0、-2 21 21 1000、3.0、-1 22 22 1000、3.0、0 23 23 1000、3.0、1 24 24 1000、3.0、2 25 25 1000、3.5、-2 26 26 1000、3.5、-1 27 1000、3.5、0 28 1000、3.5、1 29 29 1000、3.5、2
https://stackoverflow.com/questions/60270575
复制相似问题