Define the input array array = [[1], [2,3], [3], [2,4], [4], [1,4]] Define the target…
Jump to turn (6)
- 1Define the input array array = [[1], [2,3], [3], [2,4], [4], [1,4]] Define the t
- 2Can you replace the array to a dictionary like {1: [1], 2: [2, 3], 3: [3], 4: [2
- 3The processing time is still slow. My array item will normally be 1000 long list
- 4I got error from the above code :Traceback (most recent call last): File " ", li
- 5THe print result is not right. It should be like this: [2, 6]. Only the shortest
- 6Still not rigth. Please check the below code and apply the algorithm to your cod
- User
Define the input array
array = [[1], [2,3], [3], [2,4], [4], [1,4]]
Define the target set
target = {1, 2, 3, 4}
Initialize an empty list to store the results
results = []
Define a stack to store the combinations
stack = [(0, [])]
Iterate through the stack until it is empty
while stack: start, combo = stack.pop()
code# Check if the union of the current combo items is equal to the target set if set().union(*combo) == target: # Add the combo to the results list results.append(combo) # Iterate over the remaining items in the array starting from the current index for i in range(start, len(array)): # Append the next item to the combo and push it to the stack stack.append((i + 1, combo + [array[i]]))Sort the results list by the length of the combos
results.sort(key=len)
Print the results
print(“The array item combinations that can build 1, 2, 3, 4 are:”) for result in results: print(result); Can you make the code only to find the shortest combination of the result, not every one of them.