176k views
2 votes
Return a list containing all pairs of distinct elements that satisfy the function fn. Note that the pair [1, 1] should never be included in the final pairing since its elements are not distinct.

For example, all the possible pairs with disinct elements of [1, 2, 3] are [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2] but only [1, 2], [2, 1], [2, 3], [3, 2] satisfy the condition that the sum of their elements is odd.

User Klugerama
by
7.7k points

1 Answer

0 votes

Answer:

def find_pairs(lst, fn):

pairs = []

for i in range(len(lst)):

for j in range(i+1, len(lst)):

if lst[i] != lst[j] and fn(lst[i], lst[j]):

pairs.append([lst[i], lst[j]])

return pairs

Step-by-step explanation:

Here's an example Python function that takes in a list of numbers and a function, and returns a list of all pairs of distinct elements that satisfy the function:

def find_pairs(lst, fn):

pairs = []

for i in range(len(lst)):

for j in range(i+1, len(lst)):

if lst[i] != lst[j] and fn(lst[i], lst[j]):

pairs.append([lst[i], lst[j]])

return pairs

You can call this function with a list of numbers and a function that takes in two arguments and returns a boolean value. For example, to find all pairs of distinct elements whose sum is odd, you can define a function like this:

def is_sum_odd(x, y):

return (x + y) % 2 == 1

Then you can call the find_pairs function with your list and this function as arguments:

lst = [1, 2, 3]

pairs = find_pairs(lst, is_sum_odd)

print(pairs) # Output: [[1, 2], [2, 1], [2, 3], [3, 2]]

Note: this function skips pairs where both elements are the same, as well as the pair [1, 1] specifically, since it's the only pair that can be produced from a list with duplicates.

User Chamika
by
7.5k points