It is necessary to obtain all combinations of several (5) non-repeating elements of the lst list that satisfy the condition. Am I doing the right thing?

result = [] for i1 in lst[:-4]: if condition == False: continue for i2 in lst[lst.index(i1)+1:-3]: if condition == False: continue for i3 in lst[lst.index(i2)+1:-2]: if condition == False: continue for i4 in lst[lst.index(i3)+1:-1]: if condition == False: continue for i5 in lst[lst.index(i4)+1:]: if condition == False: continue result.append([i1, i2, i3, i4, i5]) 

UPD: View List

 players = [ {'name':'Вася', 'score':1.5, 'price':9.2}, {'name':'Петя', 'score':1.8, 'price':10.2}, {'name':'Коля', 'score':2.0, 'price':11.0}, {'name':'Ира', 'score':1.5, 'price':8.4}, {'name':'Аня', 'score':2.1, 'price':9.5}, {'name':'Игнат', 'score':1.4, 'price':7.0}, {'name':'Полина', 'score':2.0, 'price':14.3}, {'name':'Юра', 'score':1.6, 'price':8.4}, .......................................... ] 

The list has about 100 items. Need to get a list of combinations of 5 non-repeating elements

 combs = [{'name':'Вася', 'score':1.5, 'price':9.2}, {'name':'Ира', 'score':1.5, 'price':8.4}, {'name':'Юра', 'score':1.6, 'price':8.4}, {'name':'Игнат', 'score':1.4, 'price':7.0}, {'name':'Аня', 'score':2.1, 'price':9.5}],[...]] 

Combinations must satisfy the condition: the sum of the 'price' values ​​must not exceed a certain value. The list of combinations is necessary in order to find the combination with the maximum sum of the 'score' values.

  • @jfs edited the question - Agio
  • The edited version is similar to the task of a backpack - jfs

1 answer 1

No, wrong.

Obviously, the condition variable does not change anywhere during the iteration; accordingly, its verification does not make any sense.

If the variable check is replaced with a condition check, then it will be conditionally correct. Conditionally - because not every condition can be checked with an incomplete set, therefore it is quite possible that there should be one check before adding the set to the result. On the other hand, checks at earlier stages can significantly reduce brute force, which will speed up execution. If this is possible, then the checks in each cycle should be left, possibly replacing with others, which simply cut off the obviously bad chains.

Well and still, usually such tasks are solved recursively.

  • I meant that condition is not a variable, but some condition (for example, i1 <n, i1 + i2 <n, etc.). And recursively is it like? - Agio
  • one
    @Agio, recursively, is when a function calls itself with other parameters. Convenient for variable length. Accordingly, there will be one cycle, and if it is time to finish, then add to the result. - Qwertiy