Itertools Combinations will not output sequence larger than 3

Advertisements

In the below code I can not get the result if the output sequence is larger than 3 values.
The below code returns nothing, is there any way to get the below code to return the correct answer of 7175.90, 14259.90, 11625.47, and 3764.81?

import itertools
from decimal import Decimal

# Original list of numbers (including decimals)
numbers = [7175.90, 14259.90, 11625.47, 3764.81, 1995.27, 542.23, 2038.32, 4048.83, 490.40, 1279.00, 3248.90]

# Convert the original numbers to Decimal format
#numbers = [Decimal(num) for num in original_numbers]

target_sum = 36826.08
# Generate all combinations of the numbers
result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == target_sum]

print(result)

>Solution :

Use math.isclose – you’re using float arithmetics that is not exact:

import itertools
import math

# Original list of numbers (including decimals)
numbers = [
    7175.90,
    14259.90,
    11625.47,
    3764.81,
    1995.27,
    542.23,
    2038.32,
    4048.83,
    490.40,
    1279.00,
    3248.90,
]

target_sum = 36826.08

# Generate all combinations of the numbers
result = [
    seq
    for i in range(len(numbers), 0, -1)
    for seq in itertools.combinations(numbers, i)
    if math.isclose(sum(seq), target_sum)
]

print(result)

Prints:

[(7175.9, 14259.9, 11625.47, 3764.81)]

Leave a ReplyCancel reply