간단한 방법은 iter_tools 순열을 사용하는 것입니다
# If you are given a list
numList = [1,2,3,4,5,6,7]
# and you are asked to find the number of three sums that add to a particular number
target = 10
# How you could come up with the answer?
from itertools import permutations
good_permutations = []
for p in permutations(numList, 3):
if sum(p) == target:
good_permutations.append(p)
print(good_permutations)
결과는 다음과 같습니다.
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3,
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4,
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2),
(7, 2, 1)]
1, 2, 7을 의미하는 순서는 2, 1, 7 및 7, 1, 2로 표시됩니다. 세트를 사용하여이를 줄일 수 있습니다.