获取一段字符串的所有排列组成结果(不区分次序)

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys,math
import random
import pprint


b = "abcdef"
a = list(b)


def test(a,n):
    if n==1:
        return [i for i in a]
    length = len(a)
    res = []
    for i in range(length-n+1):
        res += [a[i] + child for child in test(a[i+1:],n-1)]
    return res

def total(a):
    res = []
    for i in range(1,len(a)+1):
        for j in test(a,i):
            res .append(j)
    return res


print(total(a))

 

 

php实现:

$a = 'abcdefg';

function test($a,$length)
{
    if(1==$length)
    {
        return str_split($a);
    }
    $res = [];
    for($i=0;$i<strlen($a)-$length+1;$i++)
    {
        $temp = test(substr($a,$i+1),$length-1);
        foreach($temp as $v)
        {
            $res[] = $a[$i].$v;
        }
    }
    return $res;
}

function total($a)
{
    $length = strlen($a);
    $res = [];
    for($i=1;$i<=$length;$i++)
    {
        foreach(test($a,$i) as $v)
        {
            $res[] = $v;
        }
    }
    return $res;
}
print_r(total($a));

 

posted @ 2017-08-03 18:58  junmo-c  阅读(225)  评论(0编辑  收藏  举报