如何将多个字符插入字符串中随机不相邻的位置

2024-10-01 17:29:18 发布

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

我正在制作一个多字字谜生成器,为此,我需要在给定的字符串中随机插入一些空格。插入的空格也不能彼此相邻,也不能位于字符串的结尾或开头。如果有人能教我怎么做,我将非常感激

这是我目前的代码:

import enchant
import itertools
d = enchant.Dict("en_US")

while True:
    text = input('Enter text to be anagrammed: ')

    perms = set([''.join(p) for p in itertools.permutations(text.replace(' ', ''))])

    anagrams = []
    for i in perms:
       if d.check(i) == True:
            anagrams.append(i)

    print(anagrams)

例如,对于输入'fartshoes',如果我想在其中插入两个空格,可能的输出是'fartshoes'


Tags: 字符串textinimporttruefor结尾enchant
1条回答
网友
1楼 · 发布于 2024-10-01 17:29:18

分而治之:

步骤1:生成将插入空间的索引集。这些索引的范围从1到k-1,其中k是输入字符串的长度。当你选择一个索引时,你必须从可能的索引集中删除它和它的相邻索引

第2步:通过在所选位置插入空格来构建最终的字符串

不需要生成所有可能的组合或使用任何组合方法

import random

s = "weholdthesetruthstobeself-evident"
n = 3

possible_spaces = set(range(1, len(s)))
spaces = set()

while len(spaces) < n and possible_spaces:
    space = random.choice(list(possible_spaces))
    spaces.add(space)
    for x in (space-1, space, space+1):
        possible_spaces.discard(x)

output = ''.join((" "+c if n in spaces else c) for n, c in enumerate(s))

print(output)

连续运行的输出:

we holdthesetru thstobeself-ev ident
weh oldthesetruthstobe self-e vident
w eholdthe setruthstobe self-evident
weholdthese tru thstobeself -evident
weholdthesetruth stobe se lf-evident
weho ld thesetruthstobe self-evident

相关问题 更多 >

    热门问题