Arrays Intersection
Now we will try to create a program that will find the intersection of the 2 arrays.
Look at the explanation of the task! How does it work?
Use hints if needed! Be careful with the tabulation!
Tarefa
Swipe to start coding
- Set while loop to work while the
left
is lower than theright
. - Set the
middle
variable. Themiddle
equals the(left + right) // 2
. - Set the condition if the middle element is greater or equals the
x
. - Update the
left
. Theleft
equals themiddle + 1
. - Create an empty array to fill it with values to test the function.
- Set for loop to work with the
nums
array. - Append the
i
to theintersection_nums
. - Print the
intersection_nums
.
Solução
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def intersection_binarySearch(x):
left, right = 0, len(nums_2)
# Set while loop to work while the 'left' is lower than the 'right'
while left < right:
# Set the 'middle' variable
middle = (left + right) // 2
# Set the condition if the middle element is greater or equals the 'x'
if nums_2[middle] >= x:
right = middle
else:
# Update the 'left'
left = middle + 1
if left < len(nums_2) and nums_2[left] == x:
return left
return -1
# Testing
nums = [1, 5, 7, 8, 8]
nums_2 = [1, 7, 8, 10, 11]
# Create an empty array to fill it with values
intersection_nums = []
# Set for loop to work with the 'nums' array
for i in set(nums):
if intersection_binarySearch(i) > -1:
# Append 'i' to the 'intersection_nums'
intersection_nums.append(i)
# Print the 'intersection_nums'
print(intersection_nums)
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 2. Capítulo 2
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def intersection_binarySearch(x):
left, right = 0, len(nums_2)
# Set while loop to work while the 'left' is lower than the 'right'
_ _ _:
# Set the 'middle' variable
middle = _ _ _
# Set the condition if the middle element is greater or equals the 'x'
_ _ _ nums_2[_ _ _] >= _ _ _:
right = middle
else:
# Update the 'left'
_ _ _
if left < len(nums_2) and nums_2[left] == x:
return left
return -1
# Testing
nums = [1, 5, 7, 8, 8]
nums_2 = [1, 7, 8, 10, 11]
# Create an empty array to fill it with values
intersection_nums = _ _ _
# Set for loop to work with the 'nums' array
_ _ _ i _ _ _ set(_ _ _):
if intersection_binarySearch(i) > -1:
# Append 'i' to the 'intersection_nums'
_ _ _.append(_ _ _)
# Print the 'intersection_nums'
print(_ _ _)
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo