2017-06-17 172 views
0

單調性百分比是數組按升序或降序排序的方式。 我需要一個Python實現這一考慮下面的例子PYTHON:numpy 2D數組排序級別的百分比

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) 

我想在人工智能啓發式運行此,速度是非常重要的(最好是numpy的)的方式,感謝您的幫助

EDITED 這是我有什麼,現在它只是返回一個布爾值,它是一維

def mncity(arr): 
    dx = np.diff(arr) 
    return np.all(dx <= 0) or np.all(dx >= 0) 

我是新來的蟒蛇一般

+3

對不起,但這不是一個編碼服務。你試過什麼了?你在哪裏掙扎? –

+0

謝謝你@ImanolLuengo –

回答

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

我喜歡這個解決方案,在想同樣的事情,但是這段代碼可以更清晰 – Netwave

+0

@DanielSanchez爲什麼不呢? 。給我你的建議,我會編輯它:-)我接受任何建議。不要猶豫:-) –

+1

你使用一個如果當代碼是相同的,但changhing 1單個運算符,也使用itertools.izip和itertools.islice而不是zip會很好,所以你不會創建中間列表只是爲了檢查,我也只是返回百分比結果:) – Netwave

1

你想利用DIFF沿着軸線(0或1),然後看正值沿此軸的比例:

(np.diff(a, axis=1) > 0).mean(axis=1) 

同樣可以爲列差異進行有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] 
+0

@Camilleri你可以請完成這個答案是可調用的嗎? –

+0

好吧,你可以定義一個返回我寫的行的函數,這很簡單。 –

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