None to Empty List

I have to find the sum of two that are equivalent to value s, can’t use dictionaries, only sets, arrays, and lists. If none, then I have to return an empty list. This is my code, I tried to remove None using if statement, but it didn’t work, not sure if it is because of the None type.

This is the code I tried

def sum_of_two(L,s):
     for item in L:
         arr = L[:]
         arr.remove(item)
         if s - item in arr:
             sOfTwo = [item, s-item]
             if sOfTwo is None:
                 return []
             else:
                 return sOfTwo

And this is the output

L= [1, 2, 5, 14, 6, 7, 8]
s = 0    sum_of_two(L,s) = None
s = 1    sum_of_two(L,s) = None
s = 2    sum_of_two(L,s) = None
s = 3    sum_of_two(L,s) = [1, 2]
s = 4    sum_of_two(L,s) = None
s = 5    sum_of_two(L,s) = None
s = 6    sum_of_two(L,s) = [1, 5]
s = 7    sum_of_two(L,s) = [1, 6]
s = 8    sum_of_two(L,s) = [1, 7]
s = 9    sum_of_two(L,s) = [1, 8]
s = 10    sum_of_two(L,s) = [2, 8]
s = 11    sum_of_two(L,s) = [5, 6]
s = 12    sum_of_two(L,s) = [5, 7]
s = 13    sum_of_two(L,s) = [5, 8]
s = 14    sum_of_two(L,s) = [6, 8]
s = 15    sum_of_two(L,s) = [1, 14]
s = 16    sum_of_two(L,s) = [2, 14]
s = 17    sum_of_two(L,s) = None
s = 18    sum_of_two(L,s) = None
s = 19    sum_of_two(L,s) = [5, 14]
s = 20    sum_of_two(L,s) = [14, 6]
s = 21    sum_of_two(L,s) = [14, 7]
s = 22    sum_of_two(L,s) = [14, 8]
s = 23    sum_of_two(L,s) = None
s = 24    sum_of_two(L,s) = None
s = 25    sum_of_two(L,s) = None
s = 26    sum_of_two(L,s) = None
s = 27    sum_of_two(L,s) = None

>Solution :

You’re missing a return statement outside of the condition. When no return value, the function will return None by default. This has nothing to do with the inner conditions you wrote, which can be deleted. I would also check if the list has less than 2 cells:

def sum_of_two(L,s):
     if len(L) < 2:
         return []
     for item in L:
         arr = L[:]
         arr.remove(item)
         if s - item in arr:
             return [item, s-item]

     return []

Leave a Reply