#Total distance values are stored here
total_dis = []
#Permutation of cooridnates
perm = permutations(result_List, num_dot)
for i in perm:
route = list(i)
route.append(route[0])
print(route)
for (x1, y1), (x2, y2) in zip(route, route[1:]):
distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(distance_formula)
I am calculating the distance between the points of each of the generated permutations.
[(5, 0), (4, 5), (2, 9), (5, 0)]
5.0990195135927845
4.47213595499958
9.486832980505138
[(5, 0), (2, 9), (4, 5), (5, 0)]
9.486832980505138
4.47213595499958
5.0990195135927845
[(4, 5), (5, 0), (2, 9), (4, 5)]
5.0990195135927845
9.486832980505138
4.47213595499958
...
I am trying to store the values of distance_formula
in lists within the list total_dis
. (I figured storing the floats in a list will allow me to find the sums of each list.) Like so:
[[5.0990195135927845, 4.47213595499958, 9.486832980505138],[9.486832980505138, 4.47213595499958, 5.0990195135927845], [5.0990195135927845, 9.486832980505138, 4.47213595499958],[...]]
I am having trouble creating the new lists for the distances between each point of each permutations to be stored.
Just add three lines
#Total distance values are stored here
total_dis = []
#Permutation of cooridnates
perm = permutations(result_List, num_dot)
for i in perm:
route = list(i)
route.append(route[0])
print(route)
dis_list = [] # <---- Add this line
for (x1, y1), (x2, y2) in zip(route, route[1:]):
distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(distance_formula)
dis_list.append(distance_formula) # <---- Add this line
total_dis.append(dis_list) # <---- Add this line (outside the "distance" loop)
You might even opt to do it as a nested list comprehension, though it might be a lot less readable.
total_dis = [
[
math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
for (x1, y1), (x2, y2) in zip(
i + (i[0], )[:-1],
i + (i[0], )[1:]
)
[
for i in permutations(result_List, num_dot)
]