You are given an array of numbers as input: [10,20,10,40,50,45,30,70,5,20,45] and a target value: 50. You are required to find pairs of elements (indices of two numbers) from the given array whose sum equals a specific target number. Your solution should not use the same element twice, thus it must be a single solution for each input
1.1 Write a Python class that defines a function to find pairs which takes 2 parameters (input array and target value) and returns a list of pairs whose sum is equal to target given above. You are required to print the list of pairs and state how many pairs if found. Your solution should call the function to find pairs, then return a list of pairs.
1.2 Given the input array nums in 1.1 above. Write a second program to find a set of good pairs from that input array nums. Here a pair (i,j) is said to be a good pair if nums[i] is the same as nums[j] and i < j. You are required to display an array of good pairs indices and the number of good pairs.
class PairsSearcher:
@staticmethod
def find_pairs(input_array, target_value):
input_array_copy = input_array.copy()
pairs = []
for i in range(len(input_array_copy) - 1):
for j in range(i + 1, len(input_array_copy)):
if input_array_copy[i] is not None and input_array_copy[j] is not None and input_array_copy[i] + input_array_copy[j] == target_value:
pairs.append((i, j))
input_array_copy[i] = None
input_array_copy[j] = None
return pairs
@staticmethod
def find_good_pairs(input_array, target_value):
good_pairs = []
for pair in PairsSearcher.find_pairs(input_array, target_value):
if pair[0] < pair[1] and input_array[pair[0]] == input_array[pair[1]]:
good_pairs.append(pair)
return good_pairs
input_array = [10, 20, 10, 40, 50, 45, 30, 70, 5, 20, 45]
target_value = 50
pairs = PairsSearcher.find_pairs(input_array, target_value)
print("{} pairs found: {}".format(len(pairs), pairs))
good_pairs = PairsSearcher.find_good_pairs(input_array, target_value)
print("{} good pairs found: {}".format(len(good_pairs), good_pairs))
Comments
Leave a comment