单调性百分比是指数组按升序或降序排序的方式。 我需要一个python(最好是numpy)方法来实现这个考虑下面的例子
$slug = str_slug($request->company_name, '-');
$validator = Validator::make(['company_name' => $slug], [
'company_name' => 'required|unique:admin_users,company_name,slug|max:191'
]);
if (!$validator->fails()) {
$db_filed->company_name = $slug;
$db_filled->save();
}
我想在AI启发式游戏中运行它,速度非常重要,感谢任何帮助
EDITED 这就是我现在所拥有的它只是返回一个bool而且它是1D
array([[2,3,4,6,5] # 60% sorted
[1,2,3,4,5] # 100% sorted
[0,2,4,8,10]# 100% sorted
[0,2,4,8,10]]# 100% sorted
/ | | \ \
/ | | \ \
100% 100% 80% 80% 100%
Monotonicity percentage is average(80,100,100,100,100,100,80,80,100)
我是PYTHON的新手
答案 0 :(得分:3)
您可以使用zip()
和list comprehension
执行此类操作:
def get_pourcent(a, order='ascending'):
if order == 'ascending':
# Check if every element is inferior than his next in the list
b = [1 if j < v else 0 for j, v in zip(a, a[1:])]
# Get how much zeros in b
zeros = len(b) - sum(b)
percent = (1 - (float(zeros)/len(a)))*100
elif order == 'descending':
b = [1 if j > v else 0 for j, v in zip(a, a[1:])]
zeros = sum(b)
percent = (float(zeros)/len(a))*100
else:
return None
return '"%s": %.2f%% sorted' % (order, percent)
# Test
tests = [('ascending', [2,3,4,6,5]), ('ascending', [1,2,3,4,5]),
('ascending', [0,2,4,8,10]), ('descending', [2,3,4,6,5]), ('descending', [0,2,4,8,10])]
for k, v in tests:
print v, get_pourcent(v, order=k)
输出:
[2, 3, 4, 6, 5] "ascending": 80.00% sorted
[1, 2, 3, 4, 5] "ascending": 100.00% sorted
[0, 2, 4, 8, 10] "ascending": 100.00% sorted
[2, 3, 4, 6, 5] "descending": 20.00% sorted
[0, 2, 4, 8, 10] "descending": 0.00% sorted
修改:
tests = [[ 2, 4, 0, 8], [ 4, 24, 0, 16], [ 16, 2, 16, 32], [ 16, 2, 16, 128]]
for k in tests:
print get_pourcent(k)
将输出:
"ascending": 75.00% sorted
"ascending": 75.00% sorted
"ascending": 75.00% sorted
"ascending": 75.00% sorted
答案 1 :(得分:1)
您想沿轴(0或1)获取差异,然后查看沿此轴的正值比例:
(np.diff(a, axis=1) > 0).mean(axis=1)
对于diff和mean中axis=0
的列,也可以这样做。
我不确定为什么你想要第一行80%而不是75%,但如果你想要,你可以这样做:
(np.diff(a, axis=1) > 0).sum(axis=1) / a.shape[1]
和列:
(np.diff(a, axis=0) > 0).sum(axis=0) / a.shape[0]
答案 2 :(得分:1)
这是我构建并按预期工作的功能
def merge(mat):
monotone = 0
matrix = numpy.copy(mat)
for i in range(4):
m_vertical = 4 if numpy.size(numpy.where(numpy.diff(matrix[:, i]) < 0)[0]) == 0 else numpy.where(numpy.diff(matrix[:, i]) < 0)[0][0]+1
m_horizontal = 4 if numpy.size(numpy.where(numpy.diff(matrix[i]) < 0)[0]) == 0 else numpy.where(numpy.diff(matrix[i]) < 0)[0][0]+1
monotone += (m_vertical + m_horizontal)*3.125
return monotone