Hamood Elholandy Hamood Elholandy - 1 year ago 81
Python Question

Sorting 2D array by Mathematical Equation

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)).

For example I have these four 2D lists:


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


the Code :

M=[ [20,10],[3,4],[5,6],[1.2,7],[6.5,4]]



print s

for i in range(0,h):

for j in range(0,w):

a[i] =s[i][j]+a[i]

Any ideas?

Answer Source

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

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)



[(3, 4), (1.2, 7), (6.5, 4), (5, 6), (20, 10)]

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download