I am completely new to Python and, trying various random bits and pieces, I hit on a problem that I think I "solved", but the code doesn't feel good - I strongly suspect what is happening to be the best way to get the desired result .
FYI - I use any latest version of Python 3 on Windows.
Problem definition
In short, what I am doing is sorting a list of pairs, so pairs containing elements that appear in the smallest pairs are sorted in front.
These pairs are in the form [i,j] with 0 <= i <= j < n , where n is the known maximum value for the elements. There are no duplicate pairs in the list.
The number of elements i is a simple calculation of the number of pairs (not paired elements) in the forms [i,j] , [j,i] and [i,i] , where j is any value that leads to a real pair.
In the sorted result, the pair [i,j] should appear before the pair [k,l] if count(i) < count(k) or count(i) == count(k) and count(j) < count(l) (If count(j) == count(l) two can be in any order - I'm not worried that sorting is stable, there will be a bonus, though).
In the sorted result, the pair [i,j] should appear before the pair [k,l] if
min(count(i),count(j)) < min(count(k),count(l)) or
min(count(i),count(j)) == min(count(k),count(l)) and max(count(i),count(j)) < max(count(k),count(l)) .
In other words, if a pair [0,1] and 1 has a count of one, but 0 has a count of four hundred, the pair should still be (or at least very close) in front of the list - they need to be sorted by the least frequent elements paired with.
Here is a far-fetched example that I built:
input [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]]
Here, each element counts the pairs of sources from which they come:
0: 1 [0,0] 1: 2 [1,2],[1,4] 2: 3 [1,2],[2,2],[2,3] 3: 3 [2,3],[3,3],[3,4] 4: 2 [1,4],[3,4]
And here is the result, along with paired points:
output: [[0,0],[1,4],[1,2],[3,4],[2,2],[2,3],[3,3]] scores: 1 1-2 1-3 2-3 3 3 3
Here 0 has a counter (it appears in one pair, although twice), therefore, in the first place. 1 has a counter of two, so the second appears - from [1,4] to [1,2] , because 4 has a counter of two and 2 has a count of three, etc.
My current solution
As I said, I believe this exercise works for sure, but it just feels like there should be a better way to do this. Anyway, here's what I still have:
#my implementation uncommented to reduce post size, see history for comments def sortPairList( data , n ): count = [] for i in range(0,n): count.append( 0 )
Any suggestions for a more "Python" way to do this?
Or is there something wrong with my current attempt?
New test case (see comments for answers)
input: [[0,0],[0,3],[0,5],[0,7],[1,1],[1,2],[1,8],[2,4],[2,5],[3,4],[3,5],[3,9],[4,4],[4,7],[4,8],[6,8],[7,7],[7,9],[8,9]] expected: [[6,8],[1,1],[1,2],[2,5],[0,5],[1,8],[3,5],[3,9],[7,9],[8,9],[2,4],[0,0],[0,3],[0,7],[7,7],[3,4],[4,7],[4,8],[4,4]]