Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

index value of the tuples

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Output: (3, 0)

Be aware that while there is a single for loop, the code is looping to construct the dictionary, it’s just not visible directly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading