python 三个数之和

def find_threedigit(arr, target):
    arr.sort()
    result = []
    for i in range(len(arr)-1):
        if arr[0] > target:
            return -1

        for j in range(i+1, len(arr)):
            temp = arr[i] + arr[j]
            if temp <= target and ((target - temp) in arr[j::]):
                print(result.append([arr[i], arr[j], target - temp]))

    return result



if __name__ == "__main__":
    arr = list(map(int, input().split()))
    target = int(input())  #测试输入的时候,写的是12,下面的结果为12 的结果
    print(find_threedigit(arr, target))

out:
2 3 4 5 6 7 12
[[2, 3, 7], [2, 4, 6], [2, 5, 5], [3, 4, 5]]
今天只来讨论一种最简单的计算三个数之和为某个数的方法,
思路是两层循环,固定其中的两个数,那么剩下的一个数也固定了,很简单的方法,大家应该可以理解



猜你喜欢

转载自blog.csdn.net/m0_37693335/article/details/81035964