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

New to Python, i am Missing an Output. goal is to find all possible outcomes from a list that sums to Zero

Problem: From a given list, i should return all possible outcomes that give a sum of 0
for a list [-1,0,1,2,-1,-4] the output should be [[-1,-1,2],[-1,0,1]]

The problem is it’s not showing all possible outcomes.

Code:

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

nums = [-1,0,1,2,-1,-4]
def three_sum():
  lst=[]
  for i in nums:             #take 3 variables
    for j in nums:
      for k in nums:
        if (nums.index(i) != nums.index(j)) and (nums.index(i) != nums.index(k)) and (nums.index(j) != nums.index(k)): 
          if i+j+k==0:
            tmp_lst=[i,j,k]
            tmp_lst.sort()
            lst.append(tmp_lst)
  for m in lst:
    while lst.count(m)>1:
      lst.remove(m)
      lst.sort()
  return lst

The expected output should be [[-1,-1,2],[-1,0,1]] but i get [[-1, 0, 1]]

>Solution :

The problem is when you check (nums.index(i) != nums.index(j)) and (nums.index(i) != nums.index(k)) and (nums.index(j) != nums.index(k)), if you have two equal numbers in the list (like two -1) then nums.index will return the index of the first one and you will discard that combination.

To solve this I changed your i, j and k to be the indexes and force them to not be equal directly in the range function.

nums = [-1, 0, 1, 2, -1, -4]


def three_sum(nums):
    lst = []
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            for k in range(j + 1, len(nums)):
                n1, n2, n3 = nums[i], nums[j], nums[k]
                if n1 + n2 + n3 == 0:
                    tmp_lst = [n1, n2, n3]
                    tmp_lst.sort()
                    lst.append(tmp_lst)

    # remove possible duplicates
    for m in lst:
        while lst.count(m) > 1:
            lst.remove(m)
            lst.sort()

    return lst


print(three_sum(nums))
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