[Python] To obtain the desired result by addition

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have fourteen numerical data and I want to reach a target number using them and just adding them.

    def find_all_sum_combinations(target, numbers):
    results = []
    for r in range(1, len(numbers) + 1): # Try combinations from 1 to the length of all numbers
    for combo in combinations(numbers, r):
    if sum(combo) == target:
    results.append(combo) # Add the appropriate combination to the list
    return results

    numbers = [2, 7, 16, 19, 33, 41, 52, 58, 60, 67, 68, 73, 85, 92]
    target = 100

    results = find_all_sum_combinations(target, numbers)

    if results:
    for result in results:
    print("+".join(map(str, result)), "=", target)
    else:
    print("NO RESULTS FOUND !")



    When the number of data is small, there is no problem and it is found within seconds, but when the number of list elements is 100 or even 1,000, the process takes minutes, even more. How can I solve this problem?

    Continue reading...

Compartilhe esta Página