Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

Using Python

Here's some requirements:

I want to find a list of of numbers [ ] that:

add up to a number (say 30)

Be within a range of (start,end) let's say (8, 20)

Have Y (say 3) elements within the list

Ex: [8,10,12]

I've tried the code below, which works for what I want, but it gives me ALL combinations which is very heavy on memory. To select one, I've just randomly selected one, however I would like to use this for bigger lists with greater ranges, so this is not efficient.

list(combinations(list(range(8,20)),3))

1 Answer

0 votes
by (25.1k points)

In python you can use the itertools module. Like this:

from itertools import combinations

for comb in combinations(range(8, 20), 3):

    if sum(comb) == 30:

        print(comb)

        break

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...