how to sum two numbers in a list?

后端 未结 7 1926
我寻月下人不归
我寻月下人不归 2021-01-29 09:17

what is the solution of this by python 3 ?

Given an array of integers, return indices of the two numbers such that they add up to a spe

7条回答
  •  半阙折子戏
    2021-01-29 09:38

    use itertools.combinations which combines the elements of your list into non-repeated couples, and check if the sum matches. If it does, print the positions of the terms:

    import itertools
    
    integer_array = [2, 8, 4, 7, 9, 5, 1]
    target = 10
    for numbers in itertools.combinations(integer_array,2):
        if sum(numbers) == target:
            print([integer_array.index(number) for number in numbers])
    

提交回复
热议问题