函数返回不完整的值

时间:2016-02-29 07:59:34

标签: python

def sum_2_array(list1):
    item = 10
    numlist = list()
    for i in list1:
        num = list1.pop()
        diff = item-num
        if diff in list1:
            return num, diff


print sum_2_array([2,3,5,8,7])

此函数计算数组元素之间的最小绝对差异。错误是它只返回一个值。 anayone请检查并告诉我哪里出错了

1 个答案:

答案 0 :(得分:0)

请运行以下代码&看看它是否有效。我用过简单的逻辑

    def sum_2_array(list1):
        item = 10
        j = 0
        for i in list1:
            print "this is value of J = ", j
            num = list1[j]
            print "this is value of num = ", num
            diff = item - num
            print "this is vale of diff = ", diff
            if diff in list1:
                print num
                print diff
            j += 1

    print sum_2_array([2, 3, 5, 8, 7])

您运行的代码,当涉及到列表中的第三项时,即5.同时,它会从列表中弹出此项。因为您使用的是list1.pop()。所以它无法在列表中找到5,这就是为什么你只得到两个值。使用我给的代码&检查它是否有效。

我从那里得到了以下结果

this is value of J =  0
this is value of num =  2
this is vale of diff =  8
2
8
this is value of J =  1
this is value of num =  3
this is vale of diff =  7
3
7
this is value of J =  2
this is value of num =  5
this is vale of diff =  5
5
5
this is value of J =  3
this is value of num =  8
this is vale of diff =  2
8
2
this is value of J =  4
this is value of num =  7
this is vale of diff =  3
7
3