Two elements of array sum - AndrewMZ6/python_cheat_sheet GitHub Wiki
Create algorithm that finds the indexes of elements whos pair sum is equals to 9.
The algo have to be smarter than just looping through every possible pair for each element
Green colored boxes are number pairs that were already checked at previous iteration
nums = [1, 3, 5, 6, 11, 23]
L = []
for i in range(len(nums) -1):
for k in range(len(nums[i + 1:])):
if nums[i] + nums[i+k+1] == 9:
L.append((i, i+k+1))
print(L)
At the first iteration i = 0
and (since len(nums)
= 6, thus i = range(6 - 1)
) it's range is i=0, 1, 2, 3, 4
The range for k
is defined by the slice len(nums[i + 1:])
and at the first iteration equals to len(nums[1:])
.
This means that we count every element that has higher index than that of the current. Sequently the range of k
is range(5) = 0, 1, 2, 3, 4. Notice that we don't subtract 1
in the second for
loop.
nums[i] + nums[i+k+1]
at the first iterations gives nums[0] + nums[1]
and as k
grows to it's biggest value the sum gives nums[0] + nums[5]
And thus the first iteration of nested for
loop os over. i
changes it's value to 2 and the nested for
loop starts again
MATLAB code
indexes = cell(0, 0);
k = 1;
a = [1, 3, 5, 6, 11, 23];
for i = 1:length(a)
for j = i + 1:length(a)
if a(i) + a(j) == 9
indexes{k} = [i, j];
k = k + 1;
end
end
end