Python:迷你字母中所有固定长度的可能单词(排列) [英] Python: all possible words (permutations) of fixed length in mini-alphabet
问题描述
假设我有一个像这样的字符串:
Let's say I have a string like so:
abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()-_+={}[]\:;"'?/>.<,`~|€
这基本上是键盘上所有字符的列表.我怎样才能得到一个由8个字符组成的单词"的所有可能组合?我知道将会有数以百万计的可能性.
This is basicly a list of all the characters on my keyboard. How could I get all possible combinations for, let's say, a "word" made up of 8 of these chars? I know there are going to be millions of possibilities.
干杯!
推荐答案
排列与组合之间的差异
您正在寻找排列或组合.
You are either looking for a permutation or a combination.
'abc'
和'bac'
是不同的排列,但是它们是相同的组合{a,b,c}
.
'abc'
and 'bac'
are different permutations, but they are the same combination {a,b,c}
.
'abc'的排列:''
,'a'
,'b'
,'c'
,'ab'
,'ba'
,'ac'
,'ca'
,'bc'
,'cb'
,'abc'
,'acb'
,'bac'
,'bca'
,'cab'
,'cba'
Permutations of 'abc': ''
, 'a'
, 'b'
, 'c'
, 'ab'
, 'ba'
, 'ac'
, 'ca'
, 'bc'
, 'cb'
, 'abc'
, 'acb'
, 'bac'
, 'bca'
, 'cab'
, 'cba'
"abc"的组合:{}
,{'a'}
,{'b'}
,{'c'}
,{'a','b'}
,{'b','c'}
,{'a','c'}
,{'a','b','c'}
Combinations of 'abc': {}
, {'a'}
, {'b'}
, {'c'}
, {'a','b'}
, {'b','c'}
, {'a','c'}
, {'a','b','c'}
在python中
使用from itertools import *
(因为那里的功能确实应该存在于默认名称空间中),或者如果您愿意的话,请使用import itertools
.
Use from itertools import *
(since the functions there really should be in the default namespace), or import itertools
if you'd like.
如果您关心排列:
permutations(yourString, 8)
如果您在意组合:
combinations(yourString, 8)
其他语言
在其他语言中,可以使用简单的递归或迭代算法来生成这些算法.请参阅Wikipedia或stackoverflow.例如 http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations
In other languages, there are simple recursive or iterative algorithms to generate these. See wikipedia or stackoverflow. e.g. http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations
重要提示
请注意,排列数量为N!
,例如,您的字符串将具有
Do note that the number of permutations is N!
, so for example your string would have
-
(69 choose 8) = 8 billion
组合的长度为8,因此...
长度为8的 -
(69 choose 8) * 8! ~= 3.37 × 10^14
排列.
(69 choose 8) = 8 billion
combinations of length 8, and therefore...(69 choose 8) * 8! ~= 3.37 × 10^14
permutations of length 8.
如果要存储每个排列,则会用完内存.即使您不这样做(因为要减少它们),也将花费很长时间才能运行,在现代计算机上可能需要1到10天.
You'll run out of memory if you are storing every permutation. Even if you don't (because you're reducing them), it'll take a long time to run, maybe somewhere between 1-10 days on a modern computer.
这篇关于Python:迷你字母中所有固定长度的可能单词(排列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!