寻找n对数字之间的最大距离(数字刻度)

时间:2016-09-02 13:21:41

标签: python

我正在尝试编写一个算法,在给定n对数字的情况下找到两个数字之间的最大距离。

这是我到目前为止所拥有的。

Wire ints是我的示例数字,第一对为1,10,第二对为1,10,第三对为7,7

wire_ints = [10, 1, 1, 10, 7, 7]
longest_cases = {}
largest_length = 0
q = 0
y = 0
leftcounter = 0
rightcounter = 1

while q < len(wire_ints):
    left_port = wire_ints[leftcounter]
    right_port = wire_ints[rightcounter]
    length_wire = left_port - right_port
    wire_length = abs(length_wire)
    leftcounter = leftcounter + 2
    rightcounter = rightcounter + 2
    q = q + 2
    y = y + 1
    if not longest_cases:
        largest_length = wire_length
        longest_cases[wire_length] = y
    elif wire_length == largest_length:
        longest_cases[wire_length] = y
    elif wire_length > largest_length:
        largest_length = wire_length
        longest_cases.clear()
        longest_cases[wire_length] = y

print(longest_cases)

目前输出{9:2},并没有错。 9是这些数字对之间的最大距离。但是,我希望它能打印{9:1, 9:2}

字典中的键指的是最大长度,值是指原始数组中对的数量。前2个整数是1对,然后是第2对2,等等。

因此,由于数组有两对长度相同,所以它应该在字典中输出BOTH对。

我无法弄清楚这一点。 救命啊!

3 个答案:

答案 0 :(得分:3)

这将获取您的初始输入并将其转换为元组列表。然后它计算元组成员之间的绝对差异并将其放入新列表中。然后,您的最终输出将创建为index_list。

wire_ints = [10, 1, 1, 10, 7, 7]

new_list = [(x,y) for (x,y) in zip(wire_ints[::2], wire_ints[1::2])]
diff_list = [abs(x[0] - x[1]) for x in new_list]
index_list = [(x, index) for (index, x) in enumerate(diff_list) if x == max(diff_list)] 

print index_list

刚刚意识到这可以进一步压缩

new_list = [abs(x-y) for (x,y) in zip(wire_ints[::2], wire_ints[1::2])]
index_list = [(x, index) for (index, x) in enumerate(diff_list) if x == max(diff_list)] 

如果您非常想要字典,最好的方法可能是将最大值存储为键,并将列号或元组中的对编号作为值。

答案 1 :(得分:2)

只要字典中只有唯一键,就应该使用对号作为键或使用列表:

wire_ints = [10, 1, 1, 10, 7, 7]

longest_dict = []
longest_so_far = 0

for i in range(len(wire_ints)//2):
  j = i*2
  a, b = wire_ints[j:j+2]
  dist = abs(a - b)
  pair = [dist, i + 1]
  if dist > longest_so_far:
    longest_so_far = dist
    longest_dict = [pair]
  elif dist == longest_so_far:
    longest_dict.append(pair)

print(longest_dict)
#=> [[9, 1], [9, 2]]

答案 2 :(得分:0)

您缺少的是不将距离索引保留在列表中。您可以通过以下代码提供:

longest_cases = {}
wire_ints = [10, 1, 1, 10, 7, 7]

leftIndex = 0
rightIndex = 1

largest_length = 0
y = 1

while leftIndex < len(wire_ints):
    cur_length = abs(wire_ints[leftIndex] - wire_ints[rightIndex])

    if cur_length in longest_cases:
        currentList = longest_cases[cur_length]
    else:
        currentList = []

    currentList.append(y)
    longest_cases[cur_length] = currentList

    leftIndex = leftIndex + 2
    rightIndex = rightIndex + 2
    y = y + 1

resultList = []
resultCase = 0
for k in longest_cases:
    if k > largest_length:
        resultList = longest_cases[k]
        resultCase = k

for index in resultList:
    print resultCase, ":", index

您可以在the link看到结果。