You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断列表能否拆分为单元素子列表与剩余元素子列表且单元素等于剩余元素和?

Solution to Split List into Two Sub-lists with Sum Condition

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:

  1. Calculate the total sum of the input list once—this avoids recalculating sums repeatedly, which keeps the solution efficient.
  2. Iterate through each element in the list, checking if it's exactly half of the total sum (since total_sum = 2 * e implies e = total_sum / 2).
  3. 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.
  4. 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]) returns False (can't split into two valid sub-lists)
  • No valid split: split_target_list([1, 2, 4]) returns False (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:43:27