python - 两个列表之间的值差异
问题描述
我正在研究一个练习题,并希望使用递归找到两个列表之间的最小差异。例如,如果我有一个列表 X,其值为 [79, 85, 10],还有一个列表 Y,如果值为 [78, 80, 87, 12],则差异将为 4。
我已经尝试遍历这两个列表,但无法弄清楚如何找到差异的最小总和,而不仅仅是返回对。
我希望这个函数返回成对的滑雪者和滑雪板,而不是代表两个给定列表之间最小差异的总和。
解决方案
这里有不同的方法,一种是暴力破解:
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
推荐阅读
- node.js - 用于 Node Angular 应用程序部署的 Google Codelab 执行失败
- c - Redis 的静态函数根本没用
- reactjs - (Git) 如何推送未做任何更改的文件?
- javascript - 如何使用 jquery 从 api 响应中检查要检查的单选和复选框的正确值
- vue.js - 将 props 从布局传递到组件
- javascript - 如何用按钮启动动画?
- css - 为什么 Chrome 开发工具不显示“计算”选项卡?
- assembly - 我对 MIPS 中 lw 指令的理解是否正确?
- javascript - 表单上的 Firefox 自动完成
- java - 来自已创建类的对象的 Java 数组