简体   繁体   English

Python或Cpp中1的排列而没有前导或尾随0

[英]Permutations of 1s without leading or trailing 0s in Python or Cpp

I need an efficient way of generating a list of lists exploring all permutations of Nx1s and Kx0s. 我需要一种有效的方法来生成列表列表,以探索Nx1和Kx0的所有排列。 However I need to remove all leading and trailing 0s and then remove the duplicates. 但是,我需要删除所有前导和尾随的0,然后删除重复项。 KN will be in the 100s, N will be anywhere between 2 and 20. KN为100,N为2至20之间的任意值。

I can do this in steps: 1) Create permutations 2) Remove trailing 0s for each list element 3) Remove leading 0s for each list element 4) Remove duplicates 我可以按以下步骤进行操作:1)创建排列2)删除每个列表元素的尾随0s 3)删除每个列表元素的前导0s 4)删除重复项

However it takes a very very long time to do the first 3 steps and so I think I need to find a different approach. 但是,执行前三个步骤需要花费非常长的时间,因此我认为我需要找到不同的方法。 Here is the code I used: 这是我使用的代码:

import itertools

def donewk(k):
  newk = []
  for i in k:
    if i not in newk:
      newk.append(i)
  return newk

n=2;
k=10;
a=(list(itertools.permutations( [1]*n+[0]*(k-2))))
for i,elem in enumerate(a):
    elem = list(elem)
    while not elem[-1]:
        elem.pop()
    while not elem[0]:
        elem.pop(0)
    a[i]=elem;

a=donewk(a)
print(a)

output 产量

[[1, 1], [1, 0, 1], [1, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]]

Answered in comments by Engineero. 在Engineero的评论中回答。

Removing leading and trailing 0s is the same thing as saying it needs to start and end with 1s. 删除前导0和尾随0就像说它需要以1开始和结束一样。 Therefor take the permutation with N-2 and then strap the 1's on the ends. 因此,使用N-2进行排列,然后将1绑在末端。

Thanks! 谢谢!

EDIT: I thought Engineero answered the question but in fact he didnt as it doesnt solve the issue of when the space between the first and last 1 in less then K. He did lead to a satisfactory answer. 编辑:我以为Engineero回答了这个问题,但实际上他没有这样做,因为它没有解决第一个和最后一个1之间的间距小于K的问题。他的确得出了令人满意的答案。

I created an iterative application. 我创建了一个迭代应用程序。 My final application is cpp, but I did a quick prototype in python as a proof of concept. 我的最终应用程序是cpp,但是我在python中做了一个快速原型作为概念证明。 Note in the cpp application instead of appending to my list I will call a separate function which uses the permutation. 请注意,在cpp应用程序中,而不是附加到我的列表中,我将调用一个使用排列的单独函数。 Feel free to critique to make it more efficient. 随时进行批评以提高效率。

import copy
aList = []

def initA(sz=10):
        return [1]+[0]*(sz-2)+[1];

def iterA(buff,level,ix):
    if (level >0):
        for i in range (level,ix):
            a=copy.deepcopy(buff)
            a[i] = 1;
            if level ==1:
                aList.append(a)
            iterA(a,level-1,i);

N=6;
K=10;
for i in range (N-2,K):
    a=initA(i+1)
    a = iterA(a,N-2,i)
print (aList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM