Hamood Elholandy Hamood Elholandy - 2 months ago 8
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:

(20,10)
(3,4)
(5,6)
(1.2,7)


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

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


the Code :

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


s=np.sqrt(M)

a=[]

print s

for i in range(0,h):

for j in range(0,w):

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


Any ideas?

Answer

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)

print(M_sorted)

OUTPUT

[(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.