Генерация всех комбинаций замененных строк - PullRequest
0 голосов
/ 04 мая 2020

У меня довольно специфический c вопрос программирования, который беспокоил меня уже пару недель, и я считаю, что это правильное место, чтобы спросить.

Мне нужна функция, которая может генерировать все комбинации различных подстрок заменяются в большей строке, например;

thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], "This is a string that says Hello and Goodbye and Hello again")

Должен возвращать

["String that says Hello, Goodbye and Hello again",
"String that says hi and Goodbye and Hello again",
"String that says hi and bye and Hello again",
"String that says Hello and bye and Hello again",
"String that says Hello, Goodbye and goodbye again",
"String that says hi and Goodbye and goodbye again",
"String that says hi and bye and goodbye again",
"String that says Hello and bye and goodbye again",]

Я пробовал различные стратегии с регулярным выражением и функцией замены, но безуспешно
Все идеи приветствуются!

Ответы [ 2 ]

3 голосов
/ 04 мая 2020

Вы можете использовать itertools.product, str.format для достижения чего-то вроде:

from itertools import product

def thisfunction(lst, s):
    for p in product(*lst):
        yield s.format(*p)

>>> list(thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], 
                      "This is a string that says {} and {} and {} again"))
['This is a string that says Hello and Goodbye and Hello again',
 'This is a string that says Hello and Goodbye and goodbye again',
 'This is a string that says Hello and bye and Hello again',
 'This is a string that says Hello and bye and goodbye again',
 'This is a string that says hi and Goodbye and Hello again',
 'This is a string that says hi and Goodbye and goodbye again',
 'This is a string that says hi and bye and Hello again',
 'This is a string that says hi and bye and goodbye again']
2 голосов
/ 04 мая 2020
from itertools import product

def thisfunction(lst, s):
    for first, *rest in lst:
        s = s.replace(first, '{}', 1)
    for p in product(*lst):
        yield s.format(*p)

print(list(thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], "This is a string that says Hello and Goodbye and Hello again")))
...