Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Finally, I have came up with my own solution, just taking half of the calculation time on average.</p> <p>The basic idea: Instead of reading and writing into the growing dictionary n^2 times, I first collect all the sums in a list. Then I sort the list. Within the sorted list, I then look for same neighbouring items.</p> <p>This is the code:</p> <pre><code>from operator import itemgetter def getPairClusters( l ): # first, we just store all possible pairs sequentially # clustering will happen later pairs = [] for i in xrange( len( l) ): for j in xrange(i+1, len( l ) ): pair = l[i] + l[j] pairs.append( ( pair, i, j ) ) pairs.sort(key=itemgetter(0)) # pairs = [ (4, 1, 3), (5, 0, 3), (7, 0, 1), (7, 2, 3), (9, 1, 2), (10, 0, 2)] # a list item of pairs now contains a tuple (like (4, 1, 3)) with # * the sum of two l items: 4 # * the index of the two l items: 1, 3 # now clustering starts # we want to find neighbouring items as # (7, 0, 1), (7, 2, 3) # (since 7=7) pairClusters = [] # flag if we are within a cluster # while iterating over pairs list withinCluster = False # iterate over pair list for i in xrange(len(pairs)-1): if not withinCluster: if pairs[i][0] == pairs[i+1][0]: # if not within a cluster # and found 2 neighbouring same numbers: # init new cluster pairCluster = [ ( pairs[i][1], pairs[i][2] ) ] withinCluster = True else: # if still within cluster if pairs[i][0] == pairs[i+1][0]: pairCluster.append( ( pairs[i][1], pairs[i][2] ) ) # else cluster has ended # (next neighbouring item has different number) else: pairCluster.append( ( pairs[i][1], pairs[i][2] ) ) pairClusters.append(pairCluster) withinCluster = False return pairClusters l = [4,3,6,1] print getPairClusters(l) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload