【问题标题】:Get the pairs of values from a list according to a condition without elements repeating根据不重复元素的条件从列表中获取值对
【发布时间】:2015-11-25 04:53:04
【问题描述】:

我有一个整数列表,例如: 1 3 4 4 9 7 10(元素个数在1到200000之间) 和一个整数变量 D,它位于 0 到 10^9 之间。 以 5 为例。

我需要计算列表中有多少对彼此之间的差异不大于变量 D 但棘手的部分是如果我取值为 1 的零元素和第一个值为 3 的元素(它们之间的差异满足条件)我不能再次使用列表的这些元素。

例如,对于上面的序列,答案是 3 对:(1,3) (4,4) (7,9)

我写了一个似乎是正确的代码,但我需要提示如何更改输入序列和变量 d 输出错误答案的方式

    list_of_colors = [1, 3, 4, 4, 9, 7, 10]
    d = 5

    number_of_pairs = 0

    list_of_colors.sort() # the values in the list are not always sorted

    i = 0 
    while True:
        if i >= len(list_of_colors): 
            break
        if i != len(list_of_colors) - 1:  
            # if the number i in list and i+1 is the same or difference between them not greater than a variable d...
            if (int(list_of_colors[i]) == int(list_of_colors[i + 1])) or abs(int(list_of_colors[i]) - int(list_of_colors[i + 1])) <= d:
                #print list_of_colors[i]," ",list_of_colors[i + 1]
                number_of_pairs += 1 # increasing the number of the acceptable pairs  
                i += 2  # jump over two elements, we already counted them
                continue
        i += 1

    print number_of_pairs

我需要另一种算法来将它与我的算法在输入序列的各种范围和变量 d 上的结果进行比较

请提出你的想法

【问题讨论】:

  • itertools 库中的 itertools.combinations(list_of_colors, 2) 函数为您提供所有不重复的组合。但我认为,这不是解决这个问题的有效方法
  • 是的,但它会输出上面示例的所有 21 种可能的组合,答案是 3 对而不是 21 对,因为我不能使用我已经使用过的列表中的元素。
  • 这个问题不是很好。如果我的列表是 1、2、3、4,而 D 是 1,那么一个解决方案是 (1, 2), (3, 4),但另一个解决方案是 (2, 3)。您是否在寻找差异最大为 D 的不相交对的最大个数?
  • Amit Kumar Gupta 抱歉,如果我没有说清楚。我需要一个最大个可能的组合而不重复它们(不是值,而是列表的确切元素)在接下来的对中,差异不大于D。在你的例子中,答案是2对.另一个例子:如果我的列表是 1,2,3,4,5,7 并且 D 是 1,那么答案是 2 对:(1,2) (3,4)。是的,最后一对可以是 (4,5) 但没关系,因为我需要一个最大数

标签: python algorithm combinations


【解决方案1】:

我对这个问题有一个贪婪的解决方案:

对输入序列进行排序。

按如下方式解析排序后的序列:

For ith element in the sequence, 
  if |a[i+1]-a[i]| <= D, 
     then pair up the elements. Proceed to process i+2th element.
  else
     proceed to process i+1th element.

【讨论】:

  • 这个代码概念和我的一样,除了我不必要的检查 int(list_of_colors[i]) == int(list_of_colors[i + 1])。 abs(int(list_of_colors[i]) - int(list_of_colors[i + 1]))
【解决方案2】:

我在这里的解决方案是首先“清理”列表,这意味着我使元素数量均匀。然后我将列表转换为元组(对)列表。 我对这个例子的结果是 3 对,以符合您的条件。

list_of_colors = [1, 3, 4, 4, 9, 7, 10]
d = 5
number_of_pairs = 0
list_of_colors.sort() # the values in the list are not always sorted

# remove the last element if the number of elements is odd
if len(list_of_colors) % 2 != 0:
    list_of_colors = list_of_colors[:-1]

# create a list of tuples
list_of_colors = [tuple(list_of_colors[i:i+2]) for i in range(0, len(list_of_colors), 2)]    

for i in list_of_colors:
    if (int(i[0]) == int(i[1])) or abs(int(i[0])) - int(i[1]) <= d:
        number_of_pairs += 1

print number_of_pairs

【讨论】:

  • 不幸的是,此代码不适用于以下情况:1,3,4 并且 d 为 1。您的代码将返回 0,实际答案为 1(元组 (3,4) 满足条件)
猜你喜欢
  • 1970-01-01
  • 2022-09-26
  • 1970-01-01
  • 2022-07-09
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
相关资源
最近更新 更多