Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara 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!

Compito

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.

Soluzione

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)

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2
single

single

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(_ _ _)

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt