在python中是否有可能以各种可能的方式重新排列字符,以及如何重新排列字符?

2024-07-01 07:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个基本程序,将单词转换成单个字符,然后以各种可能的方式拼凑所有字符。我遇到的唯一问题就是到处乱涂字符

在所有可能的方面,我的意思是,比如说你有“the”这个词,你可以有“hte”和“eth”等等

到目前为止,我的代码是:

user = input("First; ")
user2 = input("Second; ")
user3 = input("Third; ")
user4 = input("Fourth; ")
user5 = input("Fifth; ")

with open("file.txt", 'r+') as file:
    file.truncate()
    file.write(user + user2 + user3 + user4 + user5)

xy = open("file.txt", "r")
yy = xy.read()
wow = list (yy)

Tags: 程序txtinput方式open字符单词file
1条回答
网友
1楼 · 发布于 2024-07-01 07:27:20

您可以使用itertools.permutations生成字谜:

import itertools
anagrams = [''.join(x) for x in itertools.permutations(word)]

如果一个单词包含重复的字母,你会得到一些重复的字母。您可以使用set()解决此问题:

anagrams = list(set(anagrams))

相关问题 更多 >

    热门问题