write a function named sums that takes 3 arguments: 2 lists of integers nums1 and nums2, and an integer target; then return a tuple containing indices i and j of the two numbers in nums1 and nums2, respectively, where the numbers at that indices add up to target (i.e, nums1[i] + num2[j] = target). If there is no solution, return “Not found”. The function sums must contain exactly only one loop (either a for-loop or a while-loop), otherwise you will get no point. A nested-loop is considered as more than one loop.
def sums(nums1, nums2, target): nums1 = [11, 2, 15, 7, 8] nums2 = [2, 3, 4, 5] target_number = 9 for i in range(len(nums1)): for j in range(len(nums2)): total = nums1[i] + nums2[j] if total == target: a = (nums1[i], nums2[j]) print(a)
This is the code that i have written and i am struggling to get the index values can anyone please help!
You can solve it in O(n) with a dictionary and a single for loop;
nums1 = [11, 2, 15, 7, 8] nums2 = [2, 3, 4, 5] target_number = 9 def sums(nums1, nums2, target): d = dict(zip(nums2, range(len(nums2)))) for i,n in enumerate(nums1): remainder = target-n if remainder in d: return (i, d[remainder]) return 'Not found' sums(nums1, nums2, target_number)
Be aware that while there is a single
for loop, the code is looping to construct the dictionary, it’s just not visible directly.