I am attempting to get all the distances between two two lists using two for loops and an outer while loop that continues until the first list is empty. I need to obtain a list of the sum of all the individual distances from items i in list1 and items j in list2. After each iteration the first item is removed from the first list and added to the second list. This results in a number of redundant calculations.
list1 = [1, 2, 3]
list2 = [5, 6]
while len(list1) != 0:
distances = []
for i in list1:
distance = 0
for j in list2:
distance += abs(i - j)
distances.append(distance)
print(distances)
first = list1.pop(0)
list2.append(first)
The output I am getting is correct I am just looking for away to potentially speed up this process and remove these redundant calculations, potentially using memoization but I am unsure how to achieve this as I would run into issues such as (1,3) != (3,1).
The only loop that is pertinent is the outer while.
Expected output:
[9, 7, 5]
[8, 7]
[8]