how to sum two numbers in a list?

后端 未结 7 2009
我寻月下人不归
我寻月下人不归 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:53

    For each entry in the list, check whether there's any other numbers in the list after that number that add up to the target. Since a+b = target is equivalent to b = target - a, you can just take each element, look at all the numbers after that element, and check whether they are target - element. If so, return the indices.

    for index,num in  enumerate(nums):
        if target-num in nums[index+1:]:
            return(index, nums.index(target-num))
    

提交回复
热议问题