0

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?

Hamood Elholandy
  • 81
  • 1
  • 1
  • 10
  • 1
    What have you tried? I would start with [this question on sorting a list of list](http://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list) and pay particular attention to the key function – LinkBerest Sep 20 '16 at 22:34
  • Actually i started and finshed it in java on Arduino and i want to Convert it with Python – Hamood Elholandy Sep 20 '16 at 22:37
  • Java would use Comparator or just implement the Comparable interface - Python would use sorted (or just the sort method) or used a for loop so how have you tried to do this? – LinkBerest Sep 20 '16 at 22:44
  • take a look >>>> i want to apply this in python and i faced this error https://drive.google.com/file/d/0B0om5UtdFzWJZXh0aGpRSnhlTTA/view?usp=sharing – Hamood Elholandy Sep 20 '16 at 22:48
  • i want to sort by for loop but i want to acess each element in my 2D array to sort as what i want – Hamood Elholandy Sep 20 '16 at 22:49
  • Your error is due to the need for 2 more spaces on the first for loop but there are some implementation errors there (please copy and paste the code to your question too) – LinkBerest Sep 20 '16 at 22:54
  • 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] – Hamood Elholandy Sep 20 '16 at 22:58
  • Your output is longer than your input. Please [edit] your question and add the code you are using. – martineau Sep 20 '16 at 22:59
  • the code is in the Quation now (edited) – Hamood Elholandy Sep 20 '16 at 23:03

3 Answers3

1

Use the built in sort method of a list:

from math import sqrt

def dist(elem):
    return sqrt(pow(elem[0], 2) + pow(elem[1], 2))

def sorting_func(first, second):

    if dist(first) < dist(second):
        return 1
    elif dist(second) < dist(first):
        return -1
    else:
        return 0

bla= [(3, 2), (5, 4)]

bla.sort(sorting_func)

print bla
Adil Baaj
  • 21
  • 4
  • Now in Real time i have a List that printed out from Image (x,y) of some objects eny way this list can be add or remove eny Coordinate object i want it sorted like this Algourithm Automatically when eny new Coordinates is added in this list – Hamood Elholandy Sep 20 '16 at 23:38
  • when i took your great Algourithm in my Code of my List i had this error : s.sort(sorting_func) AttributeError: 'tuple' object has no attribute 'sort' – Hamood Elholandy Sep 20 '16 at 23:39
  • @HamoodElholandy your object s must be a list not a tuple, it works fine for me – Adil Baaj Sep 20 '16 at 23:59
  • @cdlane Yes i changed the name to elem, thanks for commenting – Adil Baaj Sep 21 '16 at 00:00
0

the code below will solve what you request, uncomment the print statements if you wish to see how the ordering works!!

import math
array = [(20,10), (3,4), (5,6), (1.2,7)]
sortList = []
count = 0
tempList = []
placeholder = []
#Compute the Equation of Minimum Value
for x,y in array:
    tempList.append(math.sqrt((x**2) + (y**2)))
    tempList.append(array[count])
    sortList.append(tempList)
    tempList = []
    count += 1
#Sort list
count = 1
placeholder  = sortList[0][:]
##print('ORIGINAL LIST\n', sortList)
while count < (len(sortList)):
    if sortList[count - 1][0] < sortList[count][0]:
##        print('THIS IS COUNT', count)
        count += 1
    else:
        placeholder = sortList[count - 1][:]
##        print("this is placeholder: ", placeholder)
        sortList[count - 1] = sortList[count]
##        print(sortList)
        sortList[count] = placeholder
##        print(sortList)
        placeholder = []
        count = 1
BLang
  • 930
  • 3
  • 16
  • 35
  • My sorting method would take awhile for large lists keep in mind!! – BLang Sep 20 '16 at 23:10
  • This specific comment "this loop will compute the factorial stored in variable fact" confirms my belief about the value of comments in general... – cdlane Sep 20 '16 at 23:16
  • bahaha i forgot to take that out, it was from a previous answer to another question I swear!! run my code, it works!! – BLang Sep 20 '16 at 23:19
  • Now in Real time i have a List that printed out from Image (x,y) i want it sorted like this Algourithm Automatically when eny new Coordinates is added in this list – Hamood Elholandy Sep 20 '16 at 23:27
  • Hmm i am not to sure what you mean by, "printed out by image (x,y)". but if you want to sort it after something occurs, you can make a batch file to call this script after whatever event occurs. – BLang Sep 20 '16 at 23:42
0

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.

cdlane
  • 40,441
  • 5
  • 32
  • 81
  • Now in Real time i have a List that printed out from Image (x,y) i want it sorted like this Algourithm Automatically when eny new Coordinates is added in this list – Hamood Elholandy Sep 20 '16 at 23:21
  • @HamoodElholandy, if I understand you correctly, that sounds like the making of a good followup SO question. You should include what code you have implemented so far and a pointer to this question to provide context. – cdlane Sep 20 '16 at 23:44
  • here is the Code :https://drive.google.com/file/d/0B0om5UtdFzWJd3VjNEVwVGxvWHc/view?usp=sharing here is the Error : https://drive.google.com/file/d/0B0om5UtdFzWJcG9CdGNqclBoZWM/view?usp=sharing – Hamood Elholandy Sep 20 '16 at 23:52
  • you can just print (s) and see in the output the List printed Note that im Working on Opencv 3.00 Python 2.7 pycharm idel @cdlane – Hamood Elholandy Sep 20 '16 at 23:54