Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Arrays Intersection | Problems
Binary Search in Python

book
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

  1. Set while loop to work while the left is lower than the right.
  2. Set the middle variable. The middle equals the (left + right) // 2.
  3. Set the condition if the middle element is greater or equals the x.
  4. Update the left. The left equals the middle + 1.
  5. Create an empty array to fill it with values to test the function.
  6. Set for loop to work with the nums array.
  7. Append the i to the intersection_nums.
  8. Print the intersection_nums.

Solução

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?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2
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

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt