주어진 합계로 'K' 길이 그룹을 가져와야 할 때 빈 목록, 'product' 방법, 'sum' 방법 및 'append' 방법을 사용할 수 있습니다.
예
아래는 동일한 데모입니다.
from itertools import product
my_list = [45, 32, 67, 11, 88, 90, 87, 33, 45, 32]
print("The list is : ")
print(my_list)
N = 77
print("The value of N is ")
print(N)
K = 2
print("The value of K is ")
print(K)
my_result = []
for sub in product(my_list, repeat = K):
if sum(sub) == N:
my_result.append(sub)
print("The result is : " )
print(my_result) 출력
The list is : [45, 32, 67, 11, 88, 90, 87, 33, 45, 32] The value of N is 77 The value of K is 2 The result is : [(45, 32), (45, 32), (32, 45), (32, 45), (45, 32), (45, 32), (32, 45), (32, 45)]
설명
-
필요한 패키지를 환경으로 가져옵니다.
-
목록이 정의되고 콘솔에 표시됩니다.
-
N 및 K에 대한 값이 정의되고 콘솔에 표시됩니다.
-
빈 목록이 정의되었습니다.
-
목록에 있는 요소의 곱을 결정하고 N과 동일한지 확인합니다.
-
그렇다면 빈 목록에 추가됩니다.
-
이것은 콘솔에 출력으로 표시됩니다.