繁体   English   中英

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

[英]How to restrict number of elements in list while doing itertools.combinations?

嗨,我正在写一个小项目。 我的代码的元素之一是创建工资组合。 我尝试做的是获得 4 个数字(从 0.0 到 1.0)的所有可能组合,这将给我一个 1.0 的总和。 我用 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

我想要总和为 1 的工资。我已经做到了。 我现在唯一需要做的就是在每个列表中有 4 个元素时遇到一种情况。 经常有一个 output 像“0.9,0.1”。 我希望它是“0.9,0.1,.0.0,0.0”。

希望有人能帮我解决这个问题。

如果你想采用这种格式: [0.9, 0.1, 0.0, 0.0]

这意味着值将repeat

组合的含义是它们被sorted并且它们不repeat 这是你在高中backtracking时学到的第一件事。

有一个快速的解决方案:

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

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