1

i want my output to be [i, j] for which list[i] + list[j] equals to target value. for example;

nums=[2,7,11,15]

target=9

output=[0,1] as sum of num[0]+num[1]==target

i tried my code code as;

nums=[2,7,11,15]
target=9
b=len(nums)
for i,j in zip(range(b),range(b)):
    if nums[i]+nums[j]==target:
        print(i,j)

i want to return position of element in list whose sums equals desired value, my above code does not ouput desired value, what will be best way to solve this problem?

0

5 Answers 5

3

You want to consider all values of j for each value of i. zip() doesn't do that, it just considers aligned pairs from each list, i.e., matching values of i and j. You need a nested loop, like this:

nums=[2,7,11,15]
target=9
b=len(nums)
for i in range(b):
    for j in range(b):
        if nums[i]+nums[j]==target:
            print(i,j)

You can simplify it a little by using enumerate() to get indexes and values together:

nums=[2,7,11,15]
target=9
for i, n in enumerate(nums):
    for j, m in enumerate(nums):
        if m + n == target:
            print(i,j)

There are various ways you could speed it up:

You could consider only j Indexes greater than or equal to i, and then print out both i, j and j, i when you get a match.

If you know nums is sorted, you can make it a lot faster by using a while loop that counts up from the bottom and down from the top. This would report matches when it finds them and raise the bottom counter when the sum is too low or lower the top counter when the sum is too high.

If nums is not sorted, a dictionary-based solution like @deepak-tripathi's will be most efficient. Both that and the shifting-bounds solution have O(n) solution times (vs. O(n^2) for the nested loops) and the dictionary-based solution is easier to write correctly (e.g. to handle duplicate values) and can handle sorted or unsorted lists..

Sign up to request clarification or add additional context in comments.

Comments

3

Take a look at what zip() does:

list(zip(range(4), range(4)))
[(0, 0), (1, 1), (2, 2), (3, 3)]

You're not iterating over all combinations, just the cases in which i = j. Try the itertools module, it provides many efficient iterators for situations like this.

import itertools


nums=[2,7,11,15]
target=9
b=len(nums)
for i,j in itertools.combinations(range(b), 2):
    if nums[i]+nums[j]==target:
        print(i,j)

https://docs.python.org/3/library/itertools.html#itertools.combinations

1 Comment

Thank you so much for this very helpful answer
0

I think this problem can be solved using dictionary like this : I have printed elements you can get the index as well

d_ = {}
nums=[2,7,11,15]
val  =None

for i in nums:
  if d_.get(i):
    d_[i] += 1
  else:
    d_[i] = 1

target = 17
for i in nums:
  if d_.get(target-i, None):
    val = (i,target-i)
    break

if val:
  print(nums.index(val[0]))
  print(nums.index(val[1]))

2 Comments

Your solution is simple and efficient, but not quite correct, because it shows matching values instead of their indexes. In your current version, you could replace both d_.get() calls with something like i in d_. Also, you could use a set instead of a dict, and create the set very quickly as set(nums). Or, if you want to show indexes instead of values, you could change your current code to store a list of indexes in d_ instead of a count of matching values. Then you could retrieve and print those indexes in the second loop.
@MatthiasFripp I have mentioned in the description that I have printed values. Now I have made the changes to get the index.
-1

You have to use a nested for loop.

nums = [2, 7, 11, 15]
target = 9
b = len(nums)

for i in range(b - 1):
    for j in range(i + 1, b):
        if nums[i] + nums[j] == target:
            print(i, j)

If the list is huge or the performance matters, there are a lot of optimizations you can do with this kind of problem. For example, in the above code, sort the list first, start from small numbers. If nums[i] > target, break from the outer iteration, if nums[i] + nums[j] > target, break from the inner iteration.

Comments

-2

Increment j by nums[j+1] and zip(range(b),range(b-1))

nums=[2,7,11,15]
target=9
b=len(nums)
for i,j in zip(range(b),range(b-1)):
    if nums[i]+nums[j+1]==target:
        print(i,j+1)

2 Comments

it only work for consecutive pair, if my target is 2+11=13, it wont work
got it. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.