Given a string, all possible combinations are returned

Source: Internet
Author: User
Example: ABC
Back to A,B,C,AB,AC,BC,CA,CB,ABC,ACB,BAC,BCA,CAB,CBA

Reply content:

Example: ABC
Back to A,B,C,AB,AC,BC,CA,CB,ABC,ACB,BAC,BCA,CAB,CBA

I think this is a very interesting question, as a Python fanatic, I can't agree with @garry_qian answer more, since Python offers that good standard, not to use it is too bad, in this stand, a simple, simple (and short) Well, there is no ...), but the logically is basically the same as the following:

>>> s = 'abc'>>> results = sorted([''.join(c) for l in range(len(s)) for c in permutations(s, l+1)])['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']

There is nothing special about this notation, but the use for of the two list comprehension strikes.
At the same time, it is a string list, which is closer to the original topic.

But this has stimulated some of my curiosity, and I want to write it myself, and in the same language that doesn't have these permutations, it might be easier to use the same logically album.

The first thing I accomplished was the function of the combination, which he placed into a string and returned all the characters of the length together, but did not arrange:

def get_combinations(string):    combs = []    for i in range(1, 2**len(string)):        pat = "{0:b}".format(i).zfill(len(string))        combs.append(''.join(c for c, b in zip(string, pat) if int(b)))    return combs

Tests :

>>> print get_combinations('abc')['c', 'b', 'bc', 'a', 'ac', 'ab', 'abc']

As predicted, we get:

    1. The length of the 1'c', 'b', 'a'

    2. The length of the 2'bc', 'ac', 'ab'

    3. The length of the 3'abc'

It is true that all the combinations of the various lengths are in hand.

This is certainly not the best way to write, but I think it's interesting. The idea is to consider 'abc' all the combinations, that is not to consider whether to take a , to take b and c not to take, as is the total 2*2*2 = 8 () of the 2**len(string) combination, it is not just right to:

000 -> 都不取001 -> 只取 c010 -> 只取 b011 -> 取 b c100 -> 只取 a101 -> 取 a c110 -> 取 a b111 -> 都取

So in get_combinations , a little bit of skill is used to produce two of the code from 1 to 7, and then according to 0 and 1, each group should take those characters.

It's not done yet, and we're going to have to get it from the standard answer:

All permutations of each combination

This produces get_permutations this function:

def get_permutations(clst):    if len(clst)==1:        return [clst[0]]    results = []    for idx, c in enumerate(clst):        results += [c+substr for substr in get_permutations(clst[:idx] + clst[idx+1:])]    return results

Tests :

>>> print get_permutations('abc')['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Logically is a simple, recursive way to find out 固定長度字元組合 all the permutations.

With these two kinds of function, we can find the answer:

>>> [perm for comb in get_combinations('abc') for perm in get_permutations(list(comb))]['c', 'b', 'bc', 'cb', 'a', 'ac', 'ca', 'ab', 'ba', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']

In conclusion:

    1. Don't repeat the tires, this is not only exhausting you, but also very stupid

    2. Life is short, I use Python

import itertoolschrs = 'abc'for i in range(len(chrs)):    for combination in itertools.permutations(chrs, i + 1):        print combination

Now php that you've played and python tagged, write it down in two different ways, using the same logic.

phpCode

function addChar($strs, $chars) {    $result = [];    foreach ($strs as $str) {        foreach ($chars as $char) {            $result[] = $str . $char;        }    }    return $result;}$chars  = ['a', 'b', 'c'];$group = [];$count = count($chars);for ($i = 1; $i <= $count; $i++) {     if ($i == 1) {        $group[$i] = addChar([''], $chars);    } else {        $group[$i] = addChar($group[$i - 1], $chars);    }}// 合并数组$result = call_user_func_array('array_merge', $group);var_dump($group);

pythonCode

# encoding:utf-8def addChar(strs, chars):    result = []    for str in strs:        for char in chars:            result.append(str + char)    return resultchars = ['a', 'b', 'c']group = {}count = len(chars)for i in xrange(1, count + 1):    if i == 1:        group[i] = addChar([''], chars)    else:        group[i] = addChar(group[i - 1], chars)# 合并数组result = []for i in group:    result += group[i]print result

result = [] def function(arg, string):    global result    if len(arg) >= len(string):        return None     for alphabet in string:        if alphabet in arg:            continue        function(arg+alphabet, string)        result.append(arg+alphabet)string = 'abc'for alphabet in string:    result.append(alphabet)    function(alphabet, string)print list(set(result))

python2.7, and @garry_qian the same, after writing to find out, the other floor of the Python program I am too lazy to read

# coding: utf-8import itertools as tli = ['a', 'b', 'c']tmp = []for n in range(1, len(li) + 1):    x = t.permutations(li, n)    for i in x:        tmp.append(''.join(i))print tmp

P (2,3)
P (3,3)
12 Kinds of possibilities

Assuming the length of the string is 2, then all combinations are: 2! + 2! /1! = 4
Assuming the length of the string is 3, then all combinations are: 3! + 3! /1! + 3! /2! = 15
Assuming the length of the string is 4, then all combinations are: 4! + 4! /1! + 4! /2! + 4! /3! = 64
This formula can be generalized
N! + n! /1! + n! /2! + ... + n! /(N-1)!

The code's not going to stick.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.