我如何交换1个字母并在python中给出所有可能的字母

问题描述 投票:-2回答:1

我如何只交换“一个”字母并在python3中给出所有可能的输出并追加到列表中

例如:“学习”一词我们将有所有可能的输出,如

swap the s:
tsudy, tusdy, tudsy, tudys, 
#swap the t:
tsudy, sutdy, sudty, sudyt
#also with u,d,y:
...
python python-3.x swap
1个回答
0
投票

您可以将单词转换为字符列表,

chars = list(word)

使用位置从列表中删除选定的字符

chars.pop(index)

然后在此列表的其他位置添加此字符

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

代码:

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)

结果:

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:我不会叫它"swapping",而是"moving"字符。在“交换”中​​,我宁愿替换两个字符-即。用a中的c交换abcd会得到cbad,而不是bcad(例如在“移动”中)

© www.soinside.com 2019 - 2024. All rights reserved.