如何判断列表能否拆分为单元素子列表与剩余元素子列表且单元素等于剩余元素和?
Got it, let's work through this problem together. The goal is to split a given list into two sub-lists where one sub-list is a single element that equals the sum of all elements in the other sub-list. If such a split exists, we return the pair of sub-lists; otherwise, we return False.
Approach
The key insight here is mathematical: for an element e to be equal to the sum of the rest of the list, the total sum of the original list must be 2 * e (since total sum = e + sum(remaining elements), and we need e = sum(remaining elements)).
Here's the step-by-step plan:
- Calculate the total sum of the input list once—this avoids recalculating sums repeatedly, which keeps the solution efficient.
- Iterate through each element in the list, checking if it's exactly half of the total sum (since
total_sum = 2 * eimpliese = total_sum / 2). - When we find such an element, create the two sub-lists: one containing all elements except the matching element, and the other containing just the matching element.
- If no element meets the condition after checking the entire list, return
False.
Code Example
def split_target_list(input_list): total = sum(input_list) # Iterate with index to easily slice out the target element for idx, element in enumerate(input_list): if element == total - element: # List1 is all elements except the current one; List2 is the single element list1 = input_list[:idx] + input_list[idx+1:] list2 = [element] return (list1, list2) # No valid element found return False
Test Cases
Let's test this with your example:
l = [1, 2, 3, 4, 5, 15] print(split_target_list(l)) # Output: ([1, 2, 3, 4, 5], [15])
Other test scenarios:
- Valid split with duplicate elements:
split_target_list([5, 5, 10])returns([5, 5], [10]) - Single-element list:
split_target_list([7])returnsFalse(can't split into two valid sub-lists) - No valid split:
split_target_list([1, 2, 4])returnsFalse(total sum is 7, no element equals 3.5)
Note
If you actually need the single element to be the first sub-list (e.g., return ([15], [1, 2, 3, 4, 5]) instead), just swap the order in the return statement:
return (list2, list1)
内容的提问来源于stack exchange,提问作者Piotrek Wcisło

