Skip to content
Advertisement

How to generate unto n digit combinations of an integer? [closed]

I’m trying to create a program in python which generates all the possible combinations (non-repeating) for a given number

If the input is “123”, Output should be

123,132,213,231,312,321

12,13,21,23,31,32

1,2,3

My current code is

    import itertools
    
    a=[1,2,3]
        
    for i in range(1,len(a)+1):
        print(list(itertools.combinations(a,i)))

Advertisement

Answer

You can use itertools.permutations:

import itertools

def permute_all(value):
    return [''.join(permutation) for i in range(len(value)) for permutation in itertools.permutations(value, i+1)]
    
print(permute_all('123'))
# Outputs ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement