首页 > 解决方案 > 两个列表之间的值差异

问题描述

我正在研究一个练习题,并希望使用递归找到两个列表之间的最小差异。例如,如果我有一个列表 X,其值为 [79, 85, 10],还有一个列表 Y,如果值为 [78, 80, 87, 12],则差异将为 4。

我已经尝试遍历这两个列表,但无法弄清楚如何找到差异的最小总和,而不仅仅是返回对。

我希望这个函数返回成对的滑雪者和滑雪板,而不是代表两个给定列表之间最小差异的总和。

标签: python

解决方案


这里有不同的方法,一种是暴力破解:

from itertools import combinations


def best_match_brute(skiers, skis):
    all = [list(zip(skiers, c)) for c in combinations(skis, len(skiers))]
    all_with_disparity = [(sum([abs(x-y) for x, y in result]), result) for result in all]
    # assuming the best result is any one with the lowest disparity
    return sorted(all_with_disparity )[0]


def main():
    # making sure the collections are sorted to begin with
    skiers = sorted([6, 11, 13])
    skis = sorted([5, 7, 9, 14])

    # all skiers should be able to get skis
    assert len(skis) >= len(skiers)

    print(best_match_brute(skiers, skis))


if __name__ == '__main__':
    main()

如果你坚持甚至不使用标准库函数itertools.combinations,那么我想你也可以自制,但我不明白这一点:

def combinations(xs, n):
    if n == 1:
        for x in xs:
            yield [x]
    else:
        while len(xs) >= n:
            x = xs[0]
            xs = xs[1:]
            for c in combinations(xs, n-1):
                yield [x] + c

推荐阅读