首页 > 解决方案 > How to restrict number of elements in list while doing itertools.combinations?

问题描述

Hi im writting a small project. One of the elements of my code is creating combinations of wages. What I try to do is to get all possible combinations of 4 numbers (from 0.0 to 1.0) that will give me a sum of 1.0. I loop with step = 5 to get it fast.

for i in range(0,101,5):
  wage = i/100
  l_wages.append(wage)
numbers = l_wages
result = [list(seq) for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == 1.0]
result

I want to have wages that sum up to 1. I already achived that. The only thing i need to do now is to have a situation when in every list there are 4 elements. There is often an output like "0.9,0.1". And i would like it to be "0.9,0.1,.0.0,0.0".

Hope that somebody will help me solve that problem.

标签: pythonlist

解决方案


if you want to be in this format: [0.9, 0.1, 0.0, 0.0].

it means that the values are going to repeat.

the meaning of combinations is that they are sorted and they dont repeat. that is the first thing you learn at backtracking at highschool.

there is a quick solution for you:

this solution doesnt implement combinations

l_wages = []
for i in range(0,101,5):
    wage = i/100
    l_wages.append(wage)

solutions = []
for x in l_wages:
    for y in l_wages:
        for z in l_wages:
            for w in l_wages:
                sol = [x, y, z, w]
                if sum(sol) == 1.0:
                    solutions.append(sol)

for s in solutions:
    print(s)
print(len(solutions))

output (there are a lot of solutions )

computation takes around 2-3 seconds (if you print them)

[0.0, 0.0, 0.0, 1.0]
[0.0, 0.0, 0.05, 0.95]
[0.0, 0.0, 0.1, 0.9]
[0.0, 0.0, 0.15, 0.85]
[0.0, 0.0, 0.2, 0.8]
[0.0, 0.0, 0.25, 0.75]
[0.0, 0.0, 0.3, 0.7]
...
...
...
[0.9, 0.0, 0.05, 0.05]
[0.9, 0.0, 0.1, 0.0]
[0.9, 0.05, 0.0, 0.05]
[0.9, 0.05, 0.05, 0.0]
[0.9, 0.1, 0.0, 0.0]
[0.95, 0.0, 0.0, 0.05]
[0.95, 0.0, 0.05, 0.0]
[0.95, 0.05, 0.0, 0.0]
[1.0, 0.0, 0.0, 0.0]
1680

推荐阅读