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

Python error "cannot unpack non-iterable int object"

I want to get the indexes of the elements in the list which add up to the sum.

numbers = [10,2,3,5,8,200]
sum = 12

for i,v in numbers:
    if i+v == sum:
        print(numbers[i]), print(numbers[v])
    else:
        print("other")

But I get this error:

Traceback (most recent call last):
  File "C:\User\User\PycharmProjects\training\tests.py", line 9, in <module>
    for i,v in numere:
TypeError: cannot unpack non-iterable int object

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 :

This is the infamous Two Sum problem on LeetCode, and As LeetCode states :

We can do it in one-pass. While we are iterating and inserting elements into the hash table, we also look back to check if current element’s complement already exists in the hash table. If it exists, we have found a solution and return the indices immediately.

def twoSum(nums: List[int], sum: int) -> List[int]:
        hashmap = {}
        for i in range(len(nums)):
            complement = sum - nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]]
            hashmap[nums[i]] = i

 x = twoSum(nums=numbers, sum=sum)
 print(x)
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