小编Wid*_*jet的帖子

重新排序列表以最大化相邻元素的差异

我有兴趣以这样的方式重新排序列表,以便最大化相邻元素之间差异的平方和(循环).这是一段Python代码,在阶乘时间强制解决方案,所以你可以看到我的意思:

def maximal_difference_reorder(input):

   from itertools import permutations

   best_sum = 0
   best_orderings = []

   for x in permutations(input):
        d = np.sum(np.diff(x)**2) + (x[0] - x[-1])**2
        if d > best_sum:
            best_orderings = [x]
            best_sum = d
        elif d == best_sum:
            best_orderings.append(x)

   return best_orderings
Run Code Online (Sandbox Code Playgroud)

这产生以下结果maximal_difference_reorder(range(4)):

[(0, 2, 1, 3),
 (0, 3, 1, 2),
 (1, 2, 0, 3),
 (1, 3, 0, 2),
 (2, 0, 3, 1),
 (2, 1, 3, 0),
 (3, 0, 2, 1),
 (3, 1, 2, 0)]
Run Code Online (Sandbox Code Playgroud)

如您所见,所有结果都是循环旋转和彼此反射.如果得分是用差值之和确定的,而不是平方,我相信所有排列都会得到均匀的评分,给出均匀间隔的输入.

暴力强迫效果很好,但O(n!)很糟糕,所以可以在较小的渐近计算时间内完成吗?如果它适用于不均匀的输入网格或其他评分函数,则可获得奖励积分.

顺便说一句,这不是家庭作业或面试问题,但也许它会成为一个好问题.相反,我正在尝试为一系列参数化数据生成一系列颜色,并且我试图避免彼此相邻的颜色相似.

python algorithm permutation

10
推荐指数
1
解决办法
833
查看次数

在numpy中使用蒙面数组进行索引

我有一些代码试图在另一个指定的索引处找到数组的内容,这可能指定超出前一个数组范围的索引.

input = np.arange(0, 5)
indices = np.array([0, 1, 2, 99])
Run Code Online (Sandbox Code Playgroud)

我想要做的是:打印输入[indices]并得到[0 1 2]

但这会产生异常(如预期的那样):

IndexError: index 99 out of bounds 0<=index<5
Run Code Online (Sandbox Code Playgroud)

所以我想我可以使用蒙面数组来隐藏越界索引:

indices = np.ma.masked_greater_equal(indices, 5)
Run Code Online (Sandbox Code Playgroud)

但仍然:

>print input[indices]
IndexError: index 99 out of bounds 0<=index<5
Run Code Online (Sandbox Code Playgroud)

即使:

>np.max(indices)
2
Run Code Online (Sandbox Code Playgroud)

所以我必须首先填充蒙面数组,这很烦人,因为我不知道我可以使用什么填充值来不为超出范围的那些选择任何索引:

打印输入[np.ma.filled(indices,0)]

[0 1 2 0]
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何有效地使用numpy从数组安全地选择索引而不超出输入数组的边界?

python indexing numpy

6
推荐指数
1
解决办法
3539
查看次数

标签 统计

python ×2

algorithm ×1

indexing ×1

numpy ×1

permutation ×1