Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Itertools Combinations will not output sequence larger than 3

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading