SUMAN BHATTACHARJEE
SUMAN BHATTACHARJEE

Reputation: 37

Not understanding how set iteration is working, expecting true but returning false

I am running below function but why is it returning False, 7-3 is 4 and 4 is present in the set so it should return true.

from typing import List
def find_sum_of_two(A, val):
  B = set(A)
  print("B is : " + str(B))
  for i in B:
      
      if (val - i) in B:
          return True
      else:
          return False

print(find_sum_of_two([2, 1, 4, 7, 3],7))

Upvotes: 1

Views: 106

Answers (3)

user15801675
user15801675

Reputation:

return marks the end of the function. Once the return statement is encountered, python considers that the function has ended. So all statements after return statements are unreachable.

In this, when the return True is executed, the function has ended. So else and the other return statement is not executed.

So taking advantage of the fact that any statement after return is not executed, you can remove the else part

for i in B:
    if (val - i) in B:
        return True
return False

Upvotes: 1

Corralien
Corralien

Reputation: 120391

Return False at the end of loop if your condition doesn't match:

def find_sum_of_two(A, val):
  B = set(A)
  print("B is : " + str(B))
  for i in B:
      if (val - i) in B:
          return True
  return False

print(find_sum_of_two([2, 1, 4, 7, 3],7))

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71560

return only returns once, after the first return the code does not return anymore.

So try indenting out the else like this:

from typing import List
def find_sum_of_two(A, val):
    lst = []
    B = set(A)
    print("B is : " + str(B))
    for i in B:          
        if (val - i) in B:
            return True
    else:
         return False

print(find_sum_of_two([2, 1, 4, 7, 3],7))

Actually even now the else isn't required:

    for i in B:          
        if (val - i) in B:
            return True
    return False

Upvotes: 4

Related Questions