【问题标题】:Find the difference between all the values in the array and check whether difference in present in the array查找数组中所有值之间的差异并检查数组中是否存在差异
【发布时间】:2017-01-11 21:11:49
【问题描述】:

我想写一个程序来计算一个数组的所有值之间的差异,并找出这个差异是否也存在于数组中。

例如,

a = [1,2,4,5]

for i in range(len(a)):
    j = i+1
    for j in range(len(a)):
        dif = a[i] - a[j]
        if dif in a:
            print a[i], a[j], dif

这里的输出是,

2 1 1
4 2 2
5 1 4
5 4 1

我想知道是否有更有效的方法来做到这一点?我不想在这里的内置函数中使用任何 python。没有它是否可以改进算法?

任何帮助都会有所帮助 谢谢

【问题讨论】:

  • rangelen 是我所说的“内置”函数以及打印。因此,您正在制定任意约束。
  • 此外,代码不会为您提供您提供的输出。而j = i + 1 不会做任何事情,因为你在下一行用不同的值“覆盖”j

标签: python arrays python-2.7


【解决方案1】:

您可以使用itertools.combinations 来实现:

from itertools import combinations
a = [1,2,4,5]

for i, j in combinations(a, 2):
    dif = j - i  # OR, dif = abs(j - i) for checking against absolute value
    if dif in a:
        print j, i, dif

上面的代码会打印出来:

2 1 1
5 1 4
4 2 2
5 4 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2012-01-17
    • 2015-06-27
    相关资源
    最近更新 更多