【发布时间】: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