I was asked this question on an interview. Given the following list:
[1,2,5,7,3,10,13]
Find the numbers that add up to 5.
My solution was the following:
#sort the list:
l.sort()
result = ()
for i in range(len(l)):
for j in range(i, len(l)):
if l[i] + l[j] > 5:
break
elif l[i] + l[j] == 5:
result += (l[i], l[j])
The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire