import itertools
input = [22,4,6,7,8,2,3,4,1,23,24]
target = 69
output_combination = []
output_combinations_with_replacement = []
output_permutations = []
# Based on the input we can get the target from selecting 1 or all of the input values 'select_values', consider;
# input = [69, 1, 2] output = [[69]]
# input = [68, 67, 69, 1, 2] output = [[69], [1, 68], [2, 67]]
for select_values in range(1, len(input)):
# Using itertools we pass in the input values and how many values we want to select 'r = select_values'
# Assuming input values can be repeated, we have 2 elements with 4 and as such combination [22, 4, 7, 8, 4, 24] is valid
for combination in itertools.combinations(input, r=select_values):
# We test the sum of the combination against the target and the append to output to store the result for when we finish
if sum(combination) == target:
output_combination.append(list(combination))
# If you want to repeat an element we use combinations_with_replacement, as such combiantion [23, 23, 23] is valid.
for combination in itertools.combinations_with_replacement(input, r=select_values):
if sum(combination) == target:
output_combinations_with_replacement.append(list(combination))
# If you care about the order of the elements you would use permutations, as such combination [22, 23, 24] & [22, 24, 23] & [23, 22, 24]..ect will be valid
for permutation in itertools.permutations(input, r=select_values):
if sum(permutation) == target:
output_permutations.append(list(permutation))
# Print out first 10 of each output
print('output_combination:\n', output_combination[:10], '\n\n')
print('output_combinations_with_replacement:\n', output_combinations_with_replacement[:10], '\n\n')
print('output_permutations:\n', output_permutations[:10], '\n\n')
1条答案
按热度按时间ecbunoof1#
更新了更多上下文,因此您可以自己钓鱼;-)