如何在Python中生成列表的所有排列,与该列表中的元素类型无关?
例如:
permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
Run Code Online (Sandbox Code Playgroud) 我需要一个算法,它返回一个字符串中所有字符的所有可能组合.
我试过了:
$langd = strlen($input);
for($i = 0;$i < $langd; $i++){
$tempStrang = NULL;
$tempStrang .= substr($input, $i, 1);
for($j = $i+1, $k=0; $k < $langd; $k++, $j++){
if($j > $langd) $j = 0;
$tempStrang .= substr($input, $j, 1);
}
$myarray[] = $tempStrang;
}
Run Code Online (Sandbox Code Playgroud)
但是,它只返回与字符串长度相同的数量组合.
说$input = "hey",结果将是:hey, hye, eyh, ehy, yhe, yeh.
给定PHP字符串数组,例如:
['peter', 'paul', 'mary']
Run Code Online (Sandbox Code Playgroud)
如何生成此数组元素的所有可能排列?即:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
Run Code Online (Sandbox Code Playgroud) 我整天都在看PHP数组排列/组合问题..但仍然无法弄明白:/
如果我有一个像这样的数组:
20 //key being 0
20 //key being 1
22 //key being 2
24 //key being 3
Run Code Online (Sandbox Code Playgroud)
我需要组合如:
20, 20, 22 //keys being 0 1 2
20, 20, 24 //keys being 0 1 3
20, 22, 24 //keys being 0 2 3
20, 22, 24 //keys being 1 2 3
Run Code Online (Sandbox Code Playgroud)
我目前的代码给了我:
20, 22, 24
Run Code Online (Sandbox Code Playgroud)
因为它不想重复20 ...但这就是我需要的!
这是我的代码.它直接来自Php递归以获得字符串的所有可能性
function getCombinations($base,$n){
$baselen = count($base);
if($baselen == 0){
return;
}
if($n == 1){
$return = array();
foreach($base as $b){
$return[] = …Run Code Online (Sandbox Code Playgroud) 可能重复:
排列 - 所有可能的数字集
我有一个包含选项列表的数组,每个选项都是唯一的,不能重复.
我想使用以下选项构建概率树:
$options = array('1','2','3','4','A','E','I','O');
Run Code Online (Sandbox Code Playgroud)
所以一条有效的线可能是 1-2-E-3-O-I-4-A
我怎样才能做到这一点?(或者至少指出我正确的方向!)
我正在尝试为多个输入计算数组中一组值的所有组合。类似于这个问题:
例如:
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
echo implode($output,', ');
Run Code Online (Sandbox Code Playgroud)
输出:
aa, ab, ac, ba, bb, bc, ca, cb, cc
Run Code Online (Sandbox Code Playgroud)
但问题是当我把它提升到一个更大的列表时,例如:
$chars = array('a', 'b', …Run Code Online (Sandbox Code Playgroud) 我搜索了网站,但我找不到我需要的东西,我不知道如何做这个代码.我需要一个脚本来制作数组中的所有组合
例如,我有这个数组:
$players = ('1', '2', '3', '4', '5');
Run Code Online (Sandbox Code Playgroud)
我需要这个输出
1 - 2
1 - 3
1 - 4
1 - 5
2 - 3
2 - 4
2 - 5
3 - 4
3 - 5
4 - 5
Run Code Online (Sandbox Code Playgroud)
提前致谢
php ×6
permutation ×4
algorithm ×3
combinations ×3
arrays ×1
probability ×1
python ×1
python-2.5 ×1
recursion ×1
string ×1
tree ×1