숫자 목록에서 우리는 어떤 세 요소가 결합하여 특정 합계를 낼 수 있는지 알아내고자 합니다. 우리는 그것을 삼중주라고 부릅니다. 그리고 목록에는 그러한 삼중항이 많이 있을 수 있습니다. 예를 들어 합계 10은 1,6,3 및 1,5,4에서 생성될 수 있습니다. 이 기사에서는 주어진 숫자 목록에서 이러한 세 쌍을 모두 찾는 방법을 볼 것입니다.
범위 및 임시 변수 사용
이것은 임시 변수를 생성하는 전통적인 접근 방식입니다. 이 변수는 목록의 요소를 보유하고 합계가 필요한 값과 같은지 확인합니다. 그런 다음 이러한 변수를 최종 결과 집합에 계속 누적합니다.
예시
def SumTriplets(listA, sum):
trpltcnt = 0
res = []
for i in range(0, len(listA) - 1):
s = set()
tmp = []
# Adding first element
tmp.append(listA[i])
current_sum = sum - listA[i]
for j in range(i + 1, len(listA)):
if (current_sum - listA[j]) in s:
trpltcnt += 1
# Adding second element
tmp.append(listA[j])
# Adding third element
tmp.append(current_sum - listA[j])
# Appending tuple to the final list
res.append(tuple(tmp))
tmp.pop(2)
tmp.pop(1)
s.add(listA[j])
return res
listA = [11,12,13,14,15,16,17,18,19,20]
print("Required triplets:\n",SumTriplets(listA, 40)) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Required triplets: [(11, 15, 14), (11, 16, 13), (11, 17, 12), (12, 15, 13)]
예시
from itertools import combinations
listA = [11,12,13,14,15,16,17,18,19,20]
def fsum(val):
return sum(val) == 40
res = list(filter(fsum,list(combinations(listA, 3))))
print("Required triplets:\n",res) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Required triplets: [(11, 12, 17), (11, 13, 16), (11, 14, 15), (12, 13, 15)]