Search code examples
pythonpython-3.xswap

How can I swap 1 letter and give all possible letter in python


How can I swap only "one" letter and give all possible output in python3 and append into the list

for example: the word "study" we will have all possible output like

swap the s:
tsudy, tusdy, tudsy, tudys, 
#swap the t:
tsudy, sutdy, sudty, sudyt
#also with u,d,y:
...

Solution

  • You can convert word into list of chars,

    chars = list(word)
    

    remove selected char from list using its position

    chars.pop(index)
    

    and later add this char in different places in this list

    new_chars = chars[:pos] + [char] + chars[pos:]
    

    Code:

    word = 'study'
    
    for index, char in enumerate(word):
        print('char:', char)
        # create list without selected char
        chars = list(word)
        chars.pop(index)
    
        # put selected char in different places
        for pos in range(len(chars)+1):
            # create new list 
            new_chars = chars[:pos] + [char] + chars[pos:]
            new_word = ''.join(new_chars)
    
            # skip original word
            if new_word != word:
                print(pos, '>', new_word)
    

    Result:

    char: s
    1 > tsudy
    2 > tusdy
    3 > tudsy
    4 > tudys
    char: t
    0 > tsudy
    2 > sutdy
    3 > sudty
    4 > sudyt
    char: u
    0 > ustdy
    1 > sutdy
    3 > stduy
    4 > stdyu
    char: d
    0 > dstuy
    1 > sdtuy
    2 > stduy
    4 > stuyd
    char: y
    0 > ystud
    1 > sytud
    2 > styud
    3 > stuyd
    

    BTW: I wouldn't call it "swapping" but "moving" char. In "swapping" I would rather replace two chars - ie. swapping a with c in abcd gives cbad, not bcad (like in "moving")