import random


def sorted_pairs(A, L=None):
    """ 
    Input A is an m x m matrix of pairwise preferences (numbers)
          A[i][j] is number of voters preferring i to j
          L is a subset of range(m)
    Output is a sorted list of pairs, decreasing order of strength,
          from L x L
    Uses Tidemans criterion for comparison:
       (i,j) > (k, l) if
           Aij > Akl, or
           Aij == Akl and Aji < Alk
    (Ties that still exist are broken using random numbers as tie-breakers.)
    """
    m = len(A[0])
    if L == None:
        L = range(m)
    pairs = [(A[i][j], -A[j][i], random.random(), i, j) for i in L for j in L if i != j ]
    pairs = sorted(pairs, reverse=True)
    return [(i,j) for (Aij, negAji, rand, i, j) in pairs]