🛠️ Scheduled Maintenance | We’ll be undergoing scheduled maintenance and upgrades between 00:00 PST Jan 26th until 00:00 PST Jan 28th. There may be brief interruption of services in that period. We apologize for the inconvenience.

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.
Anybody can ask a question
Anybody can answer
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

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):
 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:
return False
print(to_sum(s, target))

1 Answer

365 Team

Hi Thadaton, 
thanks for reaching out! Could you please provide a link to the lecture this question is related to? Thanks in advance. 
The 365 Team