two_sum compare for loop & while loop
Compare for loop and while loop in two sum problem, I wonder why in case of while loop needs to be len(s)-1 for the code to work as the arrow pointed out?? Do we not need to get to the last element of len(s) ???
def two_sum(s, target):
for i in range(len(s)):
for j in range(i+1, len(s)):
if s[i]+s[j]==target:
print(s[i], s[j])
return True
return False ____________________________________________________ def to_sum(s, target):
i=0
j=len(s)-1 <------------------why ???
while i <=j:
if s[i]+s[j] ==target:
print(s[i], s[j])
print(s.index(s[i]), s.index(s[j]))
return True
elif s[i]+s[j] <target:
i+=1
else: j-=1
return False
print(to_sum(s, target))
for i in range(len(s)):
for j in range(i+1, len(s)):
if s[i]+s[j]==target:
print(s[i], s[j])
return True
return False ____________________________________________________ def to_sum(s, target):
i=0
j=len(s)-1 <------------------why ???
while i <=j:
if s[i]+s[j] ==target:
print(s[i], s[j])
print(s.index(s[i]), s.index(s[j]))
return True
elif s[i]+s[j] <target:
i+=1
else: j-=1
return False
print(to_sum(s, target))
1 answers ( 0 marked as helpful)
Hi Thadaton,
thanks for reaching out! Could you please provide a link to the lecture this question is related to? Thanks in advance.
Best,
The 365 Team