w3resource

Python Exercise: Find a pair of elements from a given array whose sum equals a specific target number

Python Class: Exercise-5 with Solution

Write a Python program to find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.

Sample Solution:

Python Code:

class py_solution:
   def twoSum(self, nums, target):
        lookup = {}
        for i, num in enumerate(nums):
            if target - num in lookup:
                return (lookup[target - num], i )
            lookup[num] = i
print("index1=%d, index2=%d" % py_solution().twoSum((10,20,10,40,50,60,70),50))

Sample Output:

index1=2, index2=3  

Flowchart:

Flowchart: Find a pair of elements from a given array whose sum equals a specific target number

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to get all possible unique subsets from a set of distinct integers.
Next: Write a Python program to find the three elements that sum to zero from a set (array) of n real numbers.

What is the difficulty level of this exercise?


Python: Tips of the Day

Python: Find the number of occurrence of each values in an iterable

from collections import Counter
nums = [1, 2, 3, 3, 4, 5, 5, 1, 2, 3, 5, 1, 4, 4]
print(Counter(nums))

Output:

Counter({1: 3, 3: 3, 4: 3, 5: 3, 2: 2})
from collections import OrderedDict, Counter
y = Counter("Python Tutorial")
print(y)

Output:

Counter({'t': 2, 'o': 2, 'P': 1, 'y': 1, 'h': 1, 'n': 1, ' ': 1, 'T': 1, 'u': 1, 'r': 1, 'i': 1, 'a': 1, 'l': 1})