Sorting 2D array by Mathematical Equation
<p>I have a 2D array list that contains (x,y), however I want to sort this list by the Equation of Minimum value of (square root of (x^2 + y^2)).</p>

<p>For example I have these four 2D lists:</p>

<pre><code>(20,10)
(3,4)
(5,6)
(1.2,7)
</code></pre>

<p>If I take the square root of each 2D array in this list and return the minimum of the sorted list, the output is:</p>

<pre><code>(3,4)
(1.2,7)
(6.5,4)
(5,6)
(20,10)
</code></pre>

<p>the Code :</p>

<pre><code>M=[ [20,10],[3,4],[5,6],[1.2,7],[6.5,4]]
</code></pre>

<p>s=np.sqrt(M)</p>

<p>a=[]</p>

<p>print s</p>

<p>for i in range(0,h):</p>

<pre><code>  for j in range(0,w):

     a[i] =s[i][j]+a[i]
</code></pre>

<p>Any ideas?</p>

<p>Switch your data structure to a list of tuples and then sort using minimal value as the key function (with memoization for efficiency):</p>

<pre><code>M = [(20, 10), (3, 4), (5,6), (1.2, 7), (6.5, 4)]

def minimum_value(coordinate, dictionary={}):  # intentional dangerous default value
    if coordinate not in dictionary:
        dictionary[coordinate] = coordinate[0]**2 + coordinate[1]**2

    return dictionary[coordinate]

M_sorted = sorted(M, key=minimum_value)

print(M_sorted)
</code></pre>

<p><strong>OUTPUT</strong></p>

<pre><code>[(3, 4), (1.2, 7), (6.5, 4), (5, 6), (20, 10)]
</code></pre>

<p>Since we're only sorting, we don't need to calculate the square roots, the squares are sufficient.</p>

python arrays sorting