Home > Back-end >  I want the program to print all the possible combination
I want the program to print all the possible combination

Time:06-23

I want the program in python to print all the possible combination of a number or characters of a string. for example: 123 213 231 132 321 312 the amount is !3 but I'm not sure how to approch it. i thought of using recursion but I can't figure out how to implement it. thanks in advance!

CodePudding user response:

itertools.permutations can do this for you.

import itertools
for c in itertools.permutations('123'):
    print(''.join(c))

CodePudding user response:

We assume

X="123"

We want to find all the possible combinations.

import itertools
for c in itertools.permutations(X) :
print(''.join(c)) 

CodePudding user response:

If you'd rather not import the itertools library you can use the code from GeeksForGeeks:

def printCombination(arr, n, r):
    data = [0]*r;
    combinationUtil(arr, data, 0,
                    n - 1, 0, r);

def combinationUtil(arr, data, start,
                    end, index, r):
    if (index == r):
        for j in range(r):
            print(data[j], end = " ");
        print();
        return;

    i = start;
    while(i <= end and end - i   1 >= r - index):
        data[index] = arr[i];
        combinationUtil(arr, data, i   1,
                        end, index   1, r);
        i  = 1;

arr = [1, 2, 3, 4, 5];
r = 3;
n = len(arr);
printCombination(arr, n, r);

  • Related