how to sum two numbers in a list?

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

    The main problem with solutions testing all possible couples (with imbricated loops or itertools.combinations) is that that are O(n^2), as you basically test all possible combinations of two elements among n (there are n*(n-1)/2 such combinations) until you find a valid one.

    When n is large, you will need a more efficient algorithm. One possibility is to first sort the list (this is O(n * log(n))), finding the solution can then be done directly in O(n), which gives you a solution in O(n * log(n)).


    We sort the list first, then add the first (smallest) and last (greatest) values. If the sum is too large, we can remove the largest value. If it's too small, we remove the smallest one, until we reach the exact sum.

    We can use a collection.deque to efficiently remove values at any end of the list.

    In order to retrieve the indices, we keep them besides the values in tuples.

    from collections import deque
    
    
    def find_target(values, target):
    
        dq = deque(sorted([(val, idx) for idx, val in enumerate(values)]))
    
        while True:
            if len(dq) < 2:
                raise ValueError('No match found')
    
            s =  dq[0][0] + dq[-1][0]
    
            if s > target:
                dq.pop()
            elif s < target:
                dq.popleft()  
            else:
                break
        return dq[0], dq[-1]
    
    
    
    values = [23, 5, 55, 11, 2, 12, 26, 16]
    target = 27
    
    sol = find_target(values, target)
    
    print(sol)
    # ((11, 3), (16, 7))
    # 11 + 16 == 27, indices 3 and 7
    
    print(sol[0][1], sol[1][1])
    # 3 7
    
    0 讨论(0)
  • 2021-01-29 09:36

    This function iterates through all the numbers in the list and finds the sum with other numbers. If the sum is equal to the target, it returns the indices

    def indices_sum(nums,target):
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j] == target: return(i,j)
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
  • 2021-01-29 09:38

    We can use to pointers, at the beginning and at the end of the list to check each index by the sum of the two numbers, looping once.

    def sumOfTwo(array, target):
        i = 0
        j = len(array) - 1
        while i < j:
          add = array[i] + array[j]
          if add == target:
            return True
          elif add < target:
            i += 1
          else:
            j -= 1
        return False 
    
    input -> [1, 2, 3, 4] -> target: 6
    
     i->    <-j
    [1][2][3][4]  if i + j = target return True 
                  if i + j < target increase i
                  else decrease j
    

    Note: In a edge case, a guard of check before the loop, in case: target is a negative value, list is empty, target is null.

    0 讨论(0)
  • 2021-01-29 09:41

    This question has 2 parts:

    1. Retrieving the 2 items in a list which equate to the target
    2. Retrieving their index value

      def get_index_for_target(nums, target):

      for x in nums:
          for y in nums:
              if x + y == target:
                  return (nums.index(x), nums.index(y))
      
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题