Search code examples
pythonstringcharacterswap

Create all posible variations of string Python


I'm totally new to python but have to do some tasks using this language. The task is to create all possible variations (swapping characters in the string). My string has 2 parts: left and right, separated by '>='. So I need to change only the left part. String example is below: ab>=c. So the task is to get string ba>=c (Due to task these strings are equal) Example with more characters:

abc>=d , acb>=d , bac>=d , bca>=d , cab>=d , cba>=d

I would appreciate any help. Task seems to be pretty easy, but I have some problems with python things


Solution

  • The itertools library can help you
    Shortcode

    from itertools import permutations
    perms = [''.join(i) for i in permutations('abc')] # all possible string
    # perms == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
    

    Expanded code

    perms=[]
    for i in permutations('abc'):
        # i == ('a','b','c')
        perms+=[''.join(i)] # 'abc'