def pairwise_prefs(A,P,params,distance_bound=1):
    """
    Return a dict pref that gives for each pair (i,j) of alternatives from A
    the sum, over voters that prefer i to j, of how many positions higher i is than
    j in the voter's ballot (but not more than "distance_bound" per ballot).
    If params["missing_preferred_less"]==True:
        A short ballot is interpreted as listing the top alternatives only;
        the unlisted alternatives are preferred less than any listed alternative.
    else:
        A short ballot contributes nothing for or against the missing candidates.
    This routine also handles equals signs in ballots.
    if distance_bound is >= |A|-1, then we effectively have a Borda-type measure.
    """
    distance_bound = max(1,distance_bound)
    pref = { }
    for x in A:
        for y in A:
            pref[(x,y)] = 0
    for ballot in P:
        # compute logical "position" of each alternative on the ballot
        pos = { }                         # "position" of each alternative in the ballot (0-indexed)
        for x in A:
            pos[x] = None
        nextpos = 0                       # position of next candidate to be seen
        for x in ballot:
            if x == "=":
                nextpos = max(0,nextpos-1)
            elif pos[x] == None:
                pos[x] = nextpos
                nextpos += 1
        if params==None or params["missing_preferred_less"]:  # everything mentioned > everything not
            for x in A:
                if pos[x] == None:
                    pos[x] = nextpos
        # now compute "preference" matrix contribution for this ballot
        bound = 1
        for x in A:
            for y in A:
                if pos[x]!=None and pos[y]!=None and pos[x]<pos[y]:
                    pref[(x,y)] += P[ballot] * min( (pos[y]-pos[x]), distance_bound)
    return pref