How can I prevent the addition of the same value (with a different key) to the dictionary?

I need to populate the dictionary with pairs of key values ​​given by the following code:

for i in range(1,n+1):
    d = {}
    Ri = Vector([#SomeCoordinates])

    for k in range(1,n+1):
        Rk = Vector([#SomeCoordinates])

        if i != k:
            d['R'+str(i)+str(k)] = (Rk-Ri).mod  # Distance between Ri and Rk
        else:
            None

""" Since  (Rk-Ri).mod  gives me the distance between two points (i and k),     
it meaningless to calc the distance if i == k. """

Here's the problem:

'Rik' represents the same distance as "Rki", and I do not want to add the distance twice.

Then I tried using this code:

        if i != k and ( ('R'+str(i)+str(k)) and ('R'+str(k)+str(i)) ) not in d:
            d['R'+str(i)+str(k)] = (Rk-Ri).mod
        else:
            None

but the problem still exists.

When I "type d", I get R12, but also R21 (and the same with every pair of "i k" numbers).

What can I do?

+4
source share
3 answers

You can use the following:

d = {}
for i in range(1, n + 1):
    Ri = Vector([#SomeCoordinates]).
    for k in range(i + 1, n + 1):
        Rk = Vector([#SomeCoordinates])
        d[i, k] = d[k, i] = (Rk - Ri).mod 

, ( k > i), (i, k) (k, i).

d[i, k] d['R' + str(i) + str(k)], : , , d['R123'] (12, 3) (1, 23).

, (d = {}) , i.

+3

, . itertools.combinations .

d = {}
for i, k in itertools.combinations(range(1, n+1), 2):
    Ri = Vector([SomeCoordinates])
    Rk = Vector([SomeCoordinates])
    d['R'+str(i)+str(k)] = (Rk-Ri).mod

( ):

d = {'R'+str(i)+str(k)] : (Vector([SomeCoordinates]) - Vector([SomeCoordinates])).mod 
     for i, k in itertools.combinations(range(1, n+1), 2)}

, (, ) Vector([SomeCoordinates]) i k, ( JuniorCompressor ):

R = {i: Vector([SomeCoordinates]) for i in range(1, n+1)}
d = {(i, k): (R[i] - R[k]).mod for i, k in itertools.combinations(range(1, n+1), 2)}

, , 'R'+str(i)+str(k) , , , (1,23) (12,3), 'R123'. tuple (i,k).

+2

First, you can first set a lower value so that the previous record is automatically overwritten:

if i != k:
    key = str(i) + "," + str(k) if i < k else str(k) + "," + str(i)
    d['R'+key] = (Rk-Ri).mod

(I assume that your script only needs distance values, not information from the current keys.)

0
source

All Articles