【问题标题】:What is the most time efficient way to calculate the distance between tuples?计算元组之间距离的最省时的方法是什么?
【发布时间】:2023-01-30 22:48:54
【问题描述】:

我有一个元组列表:

tuple_list = [(1,3),(4,7),(8,1),(5,4),(9,3),(7,2),(2,7),(3,1),(8,9),(5,2)]

从这个列表中,我想返回元组中两个数字的最小距离。

在天真的方法中,我会做以下事情:

distance = 10
for tup in range(len(tuple_list)):
    if abs(tup[0]-tup[1]) < distance:
        distance = abs(tup[0]-tup[1])

然后,最后,distance 将等于 1。

但是,我怀疑有一种更快的方法来获得最小距离。我怎么能这样做?

【问题讨论】:

  • 您的算法已经是 O(n) 为什么您认为有更快的方法?或者你的意思是一种需要更少代码的方法?
  • 这是一个连续的过程,其中的计算不相互依赖。因此,我怀疑我们可以并行计算。
  • 澄清一下:在天真的方法中,存在串行依赖性。但是我们应该能够并行计算所有距离,然后返回最小值。
  • 您的代码应该无法运行,需要将 for tup in range(len(tuple_list)): 更改为 for tup in tuple_list:

标签: python list loops distance


【解决方案1】:

您可以使用排序()函数根据元素之间的差异对 tuple_list 中的元组进行排序,然后使用分钟()函数查找排序列表中的最小差异。

def min_distance(tuple_list):
    sorted_list = sorted(tuple_list, key=lambda x: abs(x[0]-x[1]))
    return abs(sorted_list[0][0]-sorted_list[0][1])

print(min_distance(tuple_list))

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多