我在21个范围内找到了可以满足a*a + b*b == c*c
的组合号,但是我不想重复组合结果。那么如何对其重新编程,而不显示重复的组合号
nums = range(1, 21)
trips = [(a, b, c) for a in nums for b in nums for c in nums if a*a + b*b == c*c]
print(trips)
答案 0 :(得分:1)
一个简单的解决方案是使用集合和排序来丢弃重复的元素:
nums = range(1, 21)
trips = sorted({(tuple(sorted((a, b))), c) for a in nums for b in nums for c in nums if a*a + b*b == c*c})
print(trips)
# [((3, 4), 5), ((5, 12), 13), ((6, 8), 10), ((8, 15), 17), ((9, 12), 15), ((12, 16), 20)]
如果要展平元组:
trips = [(a, b, c) for (a, b), c in trips]
但是,明智的做法是不要迭代a
和b
的重复组合。您可以这样做:
nums = range(1, 21)
trips = [(a, b, c) for a in nums for b in nums[a:] for c in nums if a*a + b*b == c*c]
print(trips)
# [(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
或使用itertools:
from itertools import combinations
nums = range(1, 21)
trips = [(a, b, c) for a, b in combinations(nums, 2) for c in nums if a*a + b*b == c*c]
print(trips)
# [(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
实际上也很简单。
答案 1 :(得分:1)
更长的代码,但是效率更高:我们生成a
和b
的组合而没有重复项,并使用字典来检查a**2 + b**2
是否是我们要查找的值之一,这比签入列表要快。
from itertools import combinations
maxvalue = 21
roots = {x**2:x for x in range(1, maxvalue)}
solutions = []
for a, b in combinations(range(1, maxvalue), 2):
c2 = a**2 + b**2
if c2 in roots:
solutions.append((a, b, roots[c2]))
print(solutions)
# [(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
答案 2 :(得分:0)
我建议您使用Counter,然后根据需要打印不重复的项目。
这是一个开始:
import collections
nums = range(1, 21)
trips = [(a, b, c) for a in nums for b in nums for c in nums if a*a + b*b == c*c]
counted_trips = collections.Counter(trips)
print(counted_trips)
# Then you can only print trips that have occurrency == 1 (unique)
for trip, occurrency in counted_trips.items():
if occurrency == 1:
print(trip)
输出:
Counter({(3, 4, 5): 1, (8, 6, 10): 1, (15, 8, 17): 1, (12, 5, 13): 1, (5, 12, 13): 1, (12, 16, 20): 1, (16, 12, 20): 1, (9, 12, 15): 1, (12, 9, 15): 1, (4, 3, 5): 1, (6, 8, 10): 1, (8, 15, 17): 1})
(8, 6, 10)
(15, 8, 17)
(9, 12, 15)
(16, 12, 20)
(12, 9, 15)
(8, 15, 17)
(12, 16, 20)
(4, 3, 5)
(3, 4, 5)
(12, 5, 13)
(6, 8, 10)
(5, 12, 13)
答案 3 :(得分:0)
只需依次整理a
,b
,c
,
您可以在a<b<c
if