python - 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.
解决方案
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
推荐阅读
- php - 如果我增加附件大小限制 PHP 返回空白页
- angular - Rxjs retryWhen not call [angular 5]
- python - 如何使用python包MySQLdb向MySQL数据库中插入大量元素?
- angular - Angular - 不纯管道与函数
- facebook - 应用程序在出现 #4 错误时多久进行一次 API 调用?
- vue.js - 在Vue中实时保持时间和时差
- excel - Excel 索引间接关闭工作簿
- r - `[.default`(data, subgroups[[1]]) 中的错误:无效的下标类型“符号”
- html -
将html表格提取到R中,但在多页html中跳过具有三行/行的某一列中的特定元素( ) - mongoose - 异步等待中的错误处理