This is super bad and messy, I am new to this, please help me.
Basically, I was trying to find two numbers from a list that add up to a target number.
I have set up an example with lst = [2, 4, 6, 10]
and a target value of target = 8
. The answer in this example would be (2, 6)
and (6, 2)
.
Below is my code but it is long and ugly and I am sure there is a better way of doing it. Can you please see how I can improve from my code below?
from itertools import product, permutations numbers = [2, 4, 6, 10] target_number = 8 two_nums = (list(permutations(numbers, 2))) print(two_nums) result1 = (two_nums[0][0] + two_nums[0][1]) result2 = (two_nums[1][0] + two_nums[1][1]) result3 = (two_nums[2][0] + two_nums[2][1]) result4 = (two_nums[3][0] + two_nums[3][1]) result5 = (two_nums[4][0] + two_nums[4][1]) result6 = (two_nums[5][0] + two_nums[5][1]) result7 = (two_nums[6][0] + two_nums[6][1]) result8 = (two_nums[7][0] + two_nums[7][1]) result9 = (two_nums[8][0] + two_nums[8][1]) result10 = (two_nums[9][0] + two_nums[9][1]) my_list = (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10) print (my_list) for i in my_list: if i == 8: print ("Here it is:" + str(i))
Advertisement
Answer
For every number on the list, you can look for his complementary (number that when added to the previous one would give the required target
sum). If it exists, get the pair and exit, otherwise move on.
This would look like the following:
numbers = [2, 4, 6, 10] target_number = 8 for i, number in enumerate(numbers[:-1]): # note 1 complementary = target_number - number if complementary in numbers[i+1:]: # note 2 print("Solution Found: {} and {}".format(number, complementary)) break else: # note 3 print("No solutions exist")
which produces:
Solution Found: 2 and 6
Notes:
- You do not have to check the last number; if there was a pair you would have already found it by then.
- Notice that the membership check (which is quite costly in lists) is optimized since it considers the slice
numbers[i+1:]
only. The previous numbers have been checked already. A positive side-effect of the slicing is that the existence of e.g., one4
in the list, does not give a pair for a target value of8
. - This is an excellent setup to explain the miss-understood and often confusing use of
else
infor
-loops. Theelse
triggers only if the loop was not abruptly ended by abreak
.
If the e.g., 4
– 4
solution is acceptable to you even when having a single 4
in the list you can modify as follows:
numbers = [2, 4, 6, 10] target_number = 8 for i, number in enumerate(numbers): complementary = target_number - number if complementary in numbers[i:]: print("Solution Found: {} and {}".format(number, complementary)) break else: print("No solutions exist")