December 2023
Intermediate to advanced
504 pages
11h 43m
English
Suppose you’re writing a Python application, and somewhere in your code you find that you need to get the intersection between two arrays. The intersection is a list of all the values that occur in both of the arrays. For example, if you have the arrays [3, 1, 4, 2] and [4, 5, 3, 6], the intersection would be a third array [3, 4] since both of those values are common to the two arrays.
Here’s one possible implementation:
| | def intersection(first_array, second_array): |
| | result = [] |
| | |
| | for i in first_array: |
| | for j in second_array: |
| | if i == j: |
| | result.append(i) |
| | |
| | return result |
Here, we’re running nested loops. In the outer loop, we iterate over each value in the first array. As we point to each value in ...
Read now
Unlock full access