拆分排列在所有可能的子列表上的列表

2024-05-18 14:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

一个小小的谜语:你有6张、12张、14张、15张、23张和29张卡片。有些小包有猪的卡片,有些小包有狐狸的卡片。如果你去掉一个包,猪的牌比狐狸的牌多出一倍。你必须取下哪个包

我需要遍历数据包,从列表中删除它,并在可能的子组上创建/排列以找到正确的组合

下面的代码解决了这个问题,但我得到了反复的成功,我确信存在一种更高效、更优雅的方法来编写它。请告诉我

#!/usr/bin/env python3
from itertools import permutations

packets = [6, 12, 14, 15, 23, 29]

for position, packet in enumerate(packets):
    hypothesis = list(packets)
    del(hypothesis[position])
    # the next conditional is not really needed, 
    # only use it to save some operations
    if sum(hypothesis) % 3 == 0:
        for item in permutations(hypothesis, 5):
            if sum(item[:2]) * 2 == sum(item[2:]):
               print(item[:2], "and", item[2:], "removed: ", packets[position])

Tags: 代码in列表forifpositionitem数据包

热门问题