I'm doing the famous two sum question from leet code. I noticed, if I wrote:
def findpair(num, target):
for i in range(len(num)):
for j in range(i 1, len(num)):
if num[i] ==num[j]:
continue
if num[i] num[j] == target:
return(i, j)
mylist = [1, 2, 3 ,4 ,5 , 6]
print(findpair(mylist, 7))
It only returns one pair, which is index 0 and 5.
However, if I change return
to print
, it will give me all the pair. Why is that?
CodePudding user response:
Simply because that's how functions work. when you use the return
keyword the function will stop that's why it is returning a single pair.
a better solution is to create a list and each time the condition is true you append the pair to the list. Then when the loop is finished you return the whole list which contains all the pairs.