Reputation: 90
Given Arr=[10,34,20,19]
, N=4, K=2, and to obtain the list Reqd=[[[10],[34,20,19]],[[10,34],[20,19]],[[10,34,20],[19]]]
I tried using the itertools.permutation(Arr,2)
, but did not find the desired result. How do I find the Reqd list?
Upvotes: 0
Views: 52
Reputation: 195438
Try:
Arr = [10, 34, 20, 19]
N = 4
K = 2
valid_combinations = []
def all_combinations(current):
s = sum(current)
if len(current) > K or s > N:
return
if s == N and len(current) == K:
valid_combinations.append(current)
return
for val in range(1, N + 1):
all_combinations(current + [val])
all_combinations([])
out = []
for comb in valid_combinations:
idx = 0
out.append([])
for c in comb:
out[-1].append(Arr[idx : idx + c])
idx += c
print(out)
Prints:
[[[10], [34, 20, 19]], [[10, 34], [20, 19]], [[10, 34, 20], [19]]]
For:
Arr = [10, 34, 20, 19]
N = 4
K = 3
Prints:
[[[10], [34], [20, 19]], [[10], [34, 20], [19]], [[10, 34], [20], [19]]]
Upvotes: 1