1

I have a python list like this.

[100, 150, 30, 50, 10, 20, 40]

Then I want to find 90 in list above (yes of course not in there), but my expected result are:

[50, 40]

or

[50, 30, 10]

How can I achieve that in python or other programming language?

2
  • Can you make the question more clear? Especially what your desired result is: Do you want to find any possible combination in your List or do you want to find the one with the biggest possible elements, etc? Commented May 23, 2018 at 17:36
  • @IvoVidovic I need to find only one result, not all possible combination, because it's to big if i have more than 100 value in list. Commented May 24, 2018 at 4:11

3 Answers 3

3

You can use a list comprehension to iterate over all the combinations of the list elements that sum to your target value

>>> from itertools import combinations
>>> data = [100, 150, 30, 50, 10, 20, 40]
>>> target = 90
>>> [comb for n in range(1, len(data)+1) for comb in combinations(data, n) if sum(comb) == target]
[(50, 40), (30, 50, 10), (30, 20, 40)]
Sign up to request clarification or add additional context in comments.

1 Comment

so far this is the best answer, but seems to be a problem if i have more than 100 value in list. looping combination gonna be heavy.
0

for this, you need to check each combination of numbers. for example:

take 100 and check if its less than 90, if yes, then check it with every other number less than 90 and see if they add to 90, but, if both numbers add to less than 90, check with the other numbers to see if the again add to 90.

Comments

0

Try using a list-comprehension and set:

>>> set([x for x in lst for y in lst if x+y == 90 and x != y])
{40, 50}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.