Question: Python: Write a code that checks if the sum of two numbers in a list is equal to 10. The list can be a very
Python: Write a code that checks if the sum of two numbers in a list is equal to 10. The list can be a very big list. Do not iterate through the list more than once. Do not use the brute force method.


Hint: let's say our list is [3,4,1,2,9]. In a brute force approach, you can check the first item (i.e. 3) with all the other items in the list and if that is 10, print those two items. Otherwise, try the second item and compare it with third, fourth and so on. You have to do this comparison for all the items as it is possible no two items in the list add up to 10. The problem is if the list has n list, you check each item with the other n-1 items in each iteration. Since you have n items, in total you perform n(n-1) comparisons (since you pick one of the n numbers and compare that with the remaining (n-1) numbers). But the question asks you not to iterate through the list more than once (n). How can we do that? You should use a more innovative solution. For example, you can use a dictionary that the keys are the list items and the value is 1 if (value-10-item) does not exist. For example, for a list like this: The 10-3(first value in the list)-7. We do not have 7 in the dictionary yet (we just started to populate the dictionary). So we insert the 3 in the dictionary and put 1 in its value Key value Then we calculate 10-4(second value in the list)-6. We have just 3 in the dictionary, so we go ahead and add that to the dictionary too: Key value 4 Then 10-1-9. We have 3 and 4 in the dictionary. So, let's add that to the dictionary
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
