class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ required = {} for i in range(len(nums)): if target - nums[i] in required: return [required[target - nums[i]],i] else: required[nums[i]]=i input_list = [2,8,12,15] ob1 = Solution() print(ob1.twoSum(input_list, 20))
In the above example, the function twoSum takes two arguments: nums (a list of numbers) and target (a number). The function then iterates through a list nums and creates a new dictionary named required. The function then checks if the target – value in the list is present in the dictionary required. If it is present, it returns the index of target – value and the current index. If it is not present, it adds the value in the list and the index in the dictionary.