【发布时间】:2017-12-11 22:46:17
【问题描述】:
一个小谜语:你有六包 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])
【问题讨论】:
标签: python permutation