在Python中没有重复的排列

时间:2017-05-06 05:10:33

标签: python itertools

我有N个位置,每个位置可以是0或1.我有固定数量的1,我想在这N个位置置换这些固定数量的1。

from itertools import permutations
p = [0 for k in xrange(6)]
for k in xrange(0,3):
        p[k] = 1
print(list(permutations(p)))

但是上面的结果在列表中包含四个[0,0,0,1,1,1]。我只想要其中一个。我怎样才能摆脱这些重复?

2 个答案:

答案 0 :(得分:5)

您可以获取1s的位置:

from itertools import combinations


def place_ones(size, count):
    for positions in combinations(range(size), count):
        p = [0] * size

        for i in positions:
            p[i] = 1

        yield p

行动中:

>>> list(place_ones(6, 3))
[
    [1, 1, 1, 0, 0, 0],
    [1, 1, 0, 1, 0, 0],
    [1, 1, 0, 0, 1, 0],
    [1, 1, 0, 0, 0, 1],
    [1, 0, 1, 1, 0, 0],
    [1, 0, 1, 0, 1, 0],
    [1, 0, 1, 0, 0, 1],
    [1, 0, 0, 1, 1, 0],
    [1, 0, 0, 1, 0, 1],
    [1, 0, 0, 0, 1, 1],
    [0, 1, 1, 1, 0, 0],
    [0, 1, 1, 0, 1, 0],
    [0, 1, 1, 0, 0, 1],
    [0, 1, 0, 1, 1, 0],
    [0, 1, 0, 1, 0, 1],
    [0, 1, 0, 0, 1, 1],
    [0, 0, 1, 1, 1, 0],
    [0, 0, 1, 1, 0, 1],
    [0, 0, 1, 0, 1, 1],
    [0, 0, 0, 1, 1, 1],
]

答案 1 :(得分:3)

Set非常适用于此,因为set不包含任何重复的元素:

boolean spawnTime=0;

void spawnEnemy(){
  Rectangle rect = new Rectangle();
  rect.x = Gdx.graphics.getWidth()/2;
  rect.y = Gdx.graphics.getHeight();
  rect.setSize(50,50);
  myList.add(rect);
}

spawnTime+=Gdx.graphics.getDeltaTime();

//call spawnEnemy function every second
if(spawnTime>=1){
  spawnEnemy();
  spawnTime=0;
}

//draw all the rectangles to the batch you added in the list
for(Rectangle rect: myList){
  batch.draw(rect,rect.x,rect.y,rect.w,rect.h);
}