[英]Python list of combinations of positions
I'm trying to generate a list of all possible 1-dimensional positions for an arbitrary number of identical objects. 我正在尝试为任意数量的相同对象生成所有可能的1维位置的列表。 I want it formatted so each coordinate is the distance from the previous object, so for 3 objects (0,5,2) would mean one object is at position 0, another is at position 5 and another is at position 7. 我希望它格式化,因此每个坐标是与前一个对象的距离,因此对于3个对象(0,5,2)将意味着一个对象位于位置0,另一个位于位置5而另一个位于位置7。
So the main restraint is that the sum of the coordinates is <=D. 所以主要的限制是坐标之和<= D. Nested for loops works well for this. 嵌套for循环适用于此。 For example, with 3 objects with maximum coordinate D: 例如,对于具有最大坐标D的3个对象:
def positions(D):
output=[]
for i in range(D+1):
for j in range(D+1-i):
for k in range(D+1-i-j):
output.append((i,j,k))
return(output)
What's the best way to extend this to an arbitrary number of objects? 将此扩展到任意数量的对象的最佳方法是什么? I can't find a good way without explicitly writing a specific number of for loops. 没有明确写出特定数量的for循环,我找不到一个好方法。
I think you can combine itertools.combinations
, which will give you the locations, with taking the difference, which should give you your "distance from the previous object" behaviour. 我认为你可以结合使用itertools.combinations
,它会给你带来不同的位置,这会给你“与前一个对象的距离”行为。 For example, using 例如,使用
def diff(loc):
return [y-x for x,y in zip((0,) + loc, loc)]
we have 我们有
In [114]: list(itertools.combinations(range(4), 3))
Out[114]: [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
for the possible positions , and then 对于可能的位置 ,然后
In [115]: [diff(x) for x in itertools.combinations(range(4), 3)]
Out[115]: [[0, 1, 1], [0, 1, 2], [0, 2, 1], [1, 1, 1]]
for your relative-distance version. 为您的相对距离版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.