使用python,如何查找其总和等于列表中特定数字的连续数字列表

yhxst69z  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(295)

关闭。这个问题需要更加关注。它目前不接受答案。
**想改进这个问题吗?**编辑这篇文章,更新这个问题,使它只关注一个问题。

昨天关门了。
改进这个问题
我试图得到一个连续的数字列表,它们的和等于给定的目标。
示例:输入:列表=[22,4,6,7,8,2,3,4,1,23,24]目标和=69
输出:输出列表=[22,23,24]

ecbunoof

ecbunoof1#

更新了更多上下文,因此您可以自己钓鱼;-)

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')

相关问题