The 365 Data Science team is proud to invite you to our own community forum. A very well built system to support your queries, questions and give the chance to show your knowledge and help others in their path of becoming Data Science specialists.
Ask
Anybody can ask a question
Answer
Anybody can answer
Vote
The best answers are voted up and moderated by our team

two_sum compare for loop & while loop

two_sum compare for loop & while loop

Super Learner
0
Votes
0
Answer

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))

No answers so far.
×
Learn Data Science
this Summer!
Get 50% OFF