我有一张叫做汽车的物品清单。每辆车都是一个元组,第一个元素是一个数字。我在所有汽车中找到这个数字的平均值,然后尝试将它们在中点上分成两半,使用分治算法。然而,所有的车都驶入左侧,没有一辆驶入右侧
l = sum(car[1] for car in car)/2
# all cars go in to this side
leftBeds = [car for car in cars if car[1] <= l]
# no cars go into this side
rightBeds = [car for car in cars if car[1] > l]
您需要将所有车辆数量之和除以车辆数量——而不是除以2
输出:
如果你想要一个中点,为什么不简单点呢
首先,检查代码的第一行:
它应该看起来像:
两件事:“车中有车”;如果你想要平均值,你应该用sum()除以汽车的数量
此外,任何序列(包括元组)的第一个元素的索引为[0]。如果要使用每个元组中的实际第一个元素,请将[1]替换为[0]
相关问题 更多 >
编程相关推荐