简体   繁体   English

如何在执行 itertools.combinations 时限制列表中的元素数量?

[英]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.我尝试做的是获得 4 个数字(从 0.0 到 1.0)的所有可能组合,这将给我一个 1.0 的总和。 I loop with step = 5 to get it fast.我用 step = 5 循环以使其快速。

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.我想要总和为 1 的工资。我已经做到了。 The only thing i need to do now is to have a situation when in every list there are 4 elements.我现在唯一需要做的就是在每个列表中有 4 个元素时遇到一种情况。 There is often an output like "0.9,0.1".经常有一个 output 像“0.9,0.1”。 And i would like it to be "0.9,0.1,.0.0,0.0".我希望它是“0.9,0.1,.0.0,0.0”。

Hope that somebody will help me solve that problem.希望有人能帮我解决这个问题。

if you want to be in this format: [0.9, 0.1, 0.0, 0.0] .如果你想采用这种格式: [0.9, 0.1, 0.0, 0.0]

it means that the values are going to repeat .这意味着值将repeat

the meaning of combinations is that they are sorted and they dont repeat .组合的含义是它们被sorted并且它们不repeat that is the first thing you learn at backtracking at highschool.这是你在高中backtracking时学到的第一件事。

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 ) output(有很多解决方案)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM