Exercise#

We can improve on our previous code in a few ways. One is that we can use a loop to make the distance calculation shorter.

atom_1 = [0.1, 0.5, 3.2]
atom_2 = [0.4, 0.5, 2.3]
atom_3 = [-0.3, 0.3, 1.7]
from math import sqrt
r_12 = sqrt(sum([(atom_1[i] - atom_2[i]) ** 2 for i in [0, 1, 2]]))
r_13 = sqrt(sum([(atom_1[i] - atom_3[i]) ** 2 for i in [0, 1, 2]]))
r_23 = sqrt(sum([(atom_2[i] - atom_3[i]) ** 2 for i in [0, 1, 2]]))
print(r_12, r_13, r_23)
0.9486832980505141 1.5652475842498532 0.9433981132056602

Note above we use list comprehensions to make the long equation a bit shorter.

We can also use a nested loop to iterate over each pair of atoms.

distances = []

atoms = [atom_1, atom_2, atom_3]
for i, a_i in enumerate(atoms):
    for a_j in atoms[i+1:]:
        distances.append(sqrt(sum([(a_i[k] - a_j[k]) ** 2 for k in [0, 1, 2]])))
        
print(distances)
[0.9486832980505141, 1.5652475842498532, 0.9433981132056602]

We advise you review the LOILs for a better understanding of nested loops.