Khi cần lấy nhóm độ dài 'K' với tổng cho trước, ta dùng list rỗng, phương thức product, sum và append.
Ví dụ
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)
Đầu ra
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)]
Giải thích
- Nhập
itertools.product. - Định nghĩa list, N, K, hiển thị.
- List rỗng.
- Tích các phần tử, kiểm tra tổng = N, thêm vào list rỗng.
- Hiển thị kết quả.