-2

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
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Mihnea
  • 39
  • 1
  • 7
  • What do you expect your code to do? Please add an expected result. If you're trying to iterate over the list indexes, that's not how list iteration works. – Juan C Jan 25 '22 at 14:23
  • Do you want every combination of two numbers? (if so: Does the order matter? Can you choose the same element twice?) Or do you want every adjacent pair of numbers? (if so: distinct, or overlapping?) Each of these is a common question that can probably be closed as a duplicate, but we need to know which one. – Karl Knechtel Jan 25 '22 at 14:25
  • 1
    Anyway, please read [ask]. Your question title should ideally be a *question* that describes the *problem you are trying to solve*. "How can I avoid '' in this code?" is an improvement, but "How can I iterate over ?" is much better. – Karl Knechtel Jan 25 '22 at 14:27
  • @KarlKnechtel : every combination of two numbers, not only adjacent. thank you – Mihnea Jan 25 '22 at 14:28

2 Answers2

1

You can't expect to get indices from a list item like this. Use enumerate() to accomplish it instead.

for i, v in enumerate(numbers):
1

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)
excitedmicrobe
  • 2,338
  • 1
  • 14
  • 30