Mon*_* CY 7 python iteration r permutation
我有 13 个属于不同组的列表:
A组(列表1)
B组(清单2)、(清单3)、(清单4)、(清单5)、(清单6)
C组(清单7)、(清单8)、(清单9)、(清单10)、(清单11)
D组(列表12),(列表13)
所有组的总和必须为 1
A 组可以取 0-0.7 之间的值
B 组可以取 0-0.6 之间的值
C组可以取0-0.9之间的值
D组可以取0-0.1的值
我想找到这些列表可以在不超出其组限制的情况下进行的所有不同组合。
例如:
如果对于一个组合 List2 element = 0.6,List3、List4、List5 和 List6 必须为 0
有没有简单的方法来做到这一点?(我可以使用 R 或 Python)
(列表采用从 0 到其组限制的值,增量为.1)
# i.e.
List1=[0.0,0.1,0.2,...,0.7]
List2 = [0.0,0.1,0.2,...,0.6]
# etc.
Run Code Online (Sandbox Code Playgroud)
根据新问题编辑的答案
您可以使用列表推导式,它相当快。以下代码在我的电脑上只花了几秒钟。我使用约翰科尔曼的想法首先找到每组总和的可能组合。我还使用整数而不是浮点数。要将解决方案转换回问题中所述的问题,请将每个列表值除以 10。
from itertools import product
A = range(8) # 1 value from this group
B = range(7) # 5 values from this group (with replacement)
C = range(10) # 5 values from this group (with replacement)
D = range(2) # 2 values from this group (with replacement)
# use John Coleman's idea:
# first find all possible combinations of sums per group
groupsums = [sums for sums in product(A, B, C, D) if sum(sums) == 10]
print(len(groupsums)) # -> 95
def picks(maxi, n):
"""Returns list of combinations of n integers <= maxi
that sum to maxi."""
return [combi for combi in product(range(maxi + 1), repeat=n)
if sum(combi) == maxi]
# make list of lists that each have 13 items from the above ranges,
# with constraints as stated in the question
samples = [[a, b0, b1, b2, b3, b4, c0, c1, c2, c3, c4, d0, d1]
for a, b, c, d in groupsums
for b0, b1, b2, b3, b4 in picks(b, 5)
for c0, c1, c2, c3, c4 in picks(c, 5)
for d0, d1 in picks(d, 2)]
# show the first 5 and last 5 results
for i in range(5):
print(samples[i])
print('...')
for i in range(1, 6):
print(samples[-i])
# show the number of solutions
print(len(samples))
Run Code Online (Sandbox Code Playgroud)
95
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 7, 0, 1]
...
[7, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[7, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[7, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[7, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[7, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
313027
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |