加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python重复字符的长排列

发布时间:2020-12-20 13:06:37 所属栏目:Python 来源:网络整理
导读:我正在尝试生成字符串的所有可能的排列,如“0000022222”或“000 11 2222 333”.我尝试在“0000022222”上使用itertools的排列,如下所示: from itertools import permutationsbasestring = "0"*5 +"1"*5 perms = [''.join(p) for p in permutations(basestr
我正在尝试生成字符串的所有可能的排列,如“0000022222”或“000 11 2222 333”.我尝试在“0000022222”上使用itertools的排列,如下所示:

from itertools import permutations

basestring = "0"*5 +"1"*5 
perms = [''.join(p) for p in permutations(basestring)]
print(len(perms),perms)
print(len(set(perms)),set(perms))

但是,当只有10个C 5 = 252个排列时,列表权限有300万个条目.

是否有一个我可以使用的内置工具,它更好地处理具有许多重复字符的字符串的排列?

否则,该算法如何生成排列(对于“0000 1111 222”)?

Start with 2 characters        "0000 1111"
Move right most 0 over one     "0001 0111" and add it to the list
Continue moving it to the end  "0001 1011" -> "0001 1101" -> "0001 1110"

Now move the next 0 over one   "0010 0111" -> "0010 1011"
...
Until you get to "1111 0000".

Then for each of the strings generated,repeat the process with 2's.
222 xxxx xxxx -> 22x 2xxx xxxx -> 22x x2xx xxx...

或者我最好只做set(烫发)来摆脱重复? (我需要用3-5个字符排列20个字符列表,其中itertools排列会给我10e18个字符串)

我已经随便编程了3年,但只知道有一个学期的编程课程的人.

解决方法

首先让我们看看你的第一个例子.

from itertools import permutations
basestring = "0"*5 +"1"*5

这给了basestring = [0000022222]

在没有任何参数的情况下调用置换(basestring)将给出n位置字符串的长度n的所有排列,这只是n!对于n = 10,这确实是一个很大的数字.这真的是你想要的吗?

接下来,如果要查找此长度为5的字符串的排列,则需要在对itertools.permutations的调用中指定长度为5.

perms = [''.join(p) for p in permutations(basestring,5)]

这将返回basetring中所有字符的长度为5的所有排列,而不是值.所以你会得到一些重复.

如itertools.permutations文档see Python 2 version here中所述,该函数返回的长度为n的字符串上的长度为r的排列数将为

n!/(n-r)! or in this case 30240 for n=10,r=5.

如果要删除重复项,可以使用

set(perms)

由此返回的组合的数量将是len(set(perms))= 2 ^ 5或32.这是长度为k的字符串的数量,其可以由长度为n的“字母”形成,其为n ^ k . “alphabet”是你的basetring中的唯一字符 – 其中有2个(0和1),因此你可以形成32个长度为5的唯一字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读