对于范围为(1,13)的整数,我需要构建三个总计为13的整数的所有可能变体。变体不应重复。例如(1,2,10),(2,1,10),(10,1,2)和(10,2,1)都是一个变体的重复。因此,结果列表应仅具有该元组之一,而与哪一个无关。
到目前为止,我已经有了这段代码,该代码会生成我需要删除的所有可能的重复:
ages = list(range(1,13))
kids_ages = []
for a in ages:
for b in ages:
for c in ages:
if a + b + c == 13:
kids_ages.append((a,b,c))
结果我得到:
([(1, 1, 11),
(1, 2, 10),
(1, 3, 9),
(1, 4, 8),
(1, 5, 7),
(1, 6, 6),
(1, 7, 5),
(1, 8, 4),
(1, 9, 3),
(1, 10, 2),
(1, 11, 1),
(2, 1, 10),
(2, 2, 9),
(2, 3, 8),
...
如何消除重复?
frozenset可以在这里帮助您删除重复项。
ages = list(range(1,13))
kids_ages = []
for a in ages:
for b in ages:
for c in ages:
if a + b + c == 13:
kids_ages.append((a,b,c))
result=set(map(frozenset, kids_ages))
print(result)
我仅考虑第一位置的最低年龄和第二位置的第二最低年龄来解决这个问题。这样,就不必查找重复项。
ages = list(range(1,13))
kids_ages = []
# First, pick the smallest age
for age1 in range(1,13):
remaining_sum = 13 - age1
# Pick the next smallest age
for age2 in range(age1 + 1, 13):
age3 = 13 - age1 - age2
if age3 > age1 and age3 > age2:
kids_ages.append( (age1, age2, age3) )
print kids_ages
# Result:
# [(1, 2, 10), (1, 3, 9), (1, 4, 8), (1, 5, 7), (2, 3, 8), (2, 4, 7), (2, 5, 6), (3, 4, 6)]