【问题标题】:Replace '#' in a string with a set of characters, give all possible string combinations [closed]用一组字符替换字符串中的“#”,给出所有可能的字符串组合[关闭]
【发布时间】:2021-12-15 22:01:54
【问题描述】:

问题:
将字符串 S 中的“#”替换为一组字符。替换后生成所有可能的字符串组合。

示例 1:
字符串 = "a#b"
字符集 = {1,2,3}
可能的字符串是“a1b”、“a2b”、“a3b”

示例 2:
字符串 = "##b"
字符集 = {1,2}
可能的字符串是“11b”、“22b”、“12b”、“21b”

我的工作:
使用单个“#”很明显,我能够做到,但是当字符串像“a#bcd#ef#”时,我没有继续进行的想法。

谁能提供一个算法和工作代码(可能在python中)

【问题讨论】:

  • 你做了什么?请提供您的代码,以便我们提供帮助!

标签: python string algorithm replace string-concatenation


【解决方案1】:

您可以使用itertools.product 生成可能的字符串组合,然后使用迭代器(和next)技巧将# 替换为字符。

import itertools

def fill_pounds(s, chars):
    for p in map(iter, itertools.product(chars, repeat=s.count('#'))):
        yield ''.join(c if c != '#' else next(p) for c in s)

print(*fill_pounds('a#b', '123'))
print(*fill_pounds('##b', '12'))
print(*fill_pounds('f##k', 'or'))

输出:

a1b a2b a3b
11b 12b 21b 22b
fook fork frok frrk

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2012-08-01
    • 2018-06-29
    • 2012-04-25
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多