I'm working on a practice problem, and want to find the minimum disparity between the two lists using recursion.For example, if I have a list, X, with values [79, 85, 10], and a list, Y, with values [78, 80, 87, 12], the disparity will be 4.
I've tried iterating through both lists, and can't figure out how to just find the minimum sum of the disparity, rather than only returning the pairs.
I expect this function to return pairs of skiers and skis, but not the sum representing the minimum disparity between two given lists.
One solution is to use NumPy to find the closest value in the skis list (NumPy function borrowed from Find nearest value in numpy array). Then go through the skiers and find the closest size. Remember to then remove that size from the list.
import numpy as np
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array-value)).argmin()
return array[idx]
def pair(x, y):
skier_skis = []
skis_left = list(y)
for skier in x:
skier_skis.append((skier, find_nearest(skis_left, skier)))
skis_left.remove(skier_skis[-1][1])
return skier_skis
skiers = [6, 11, 13]
skis = [5, 7, 9, 14]
pair(skiers, skis)
returns [(6, 5), (11, 9), (13, 14)].
If your goal is to just return the minimum disparity, then iterate through the skier_skis list and sum the difference.
edit: as @Rivers Shall points out, this may not always return the optimal solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With