Create all possible replacements

Given a replacement map of type {search: replace, search: replace, ...} and a line, how to generate a list of all possible replacements for this line (the first substring is replaced, the second substring is replaced and replaced, etc.). Example:

 map = { 'bee': 'BETA', 'zee': 'ZETA', 'dee': 'DELTA' } source_string = 'bee foo zee bar bee' desired result = [ 'bee foo zee bar bee', 'BETA foo zee bar bee', 'bee foo ZETA bar bee', 'BETA foo ZETA bar bee', 'bee foo zee bar BETA', 'BETA foo zee bar BETA', 'bee foo ZETA bar BETA', 'BETA foo ZETA bar BETA' ] 

Order is not important.

+6
source share
2 answers

'bee foo zee bar bee' => ['bee', 'foo', 'zee', 'bar', 'bee'] :

 from itertools import product repl = { 'bee': 'BETA', 'zee': 'ZETA', 'dee': 'DELTA' } source_string = 'bee foo zee bar bee' p = product(*((x, repl[x]) if x in repl else (x,) for x in source_string.split())) for x in p: print(x) 

Output:

 ('bee', 'foo', 'zee', 'bar', 'bee') ('bee', 'foo', 'zee', 'bar', 'BETA') ('bee', 'foo', 'ZETA', 'bar', 'bee') ('bee', 'foo', 'ZETA', 'bar', 'BETA') ('BETA', 'foo', 'zee', 'bar', 'bee') ('BETA', 'foo', 'zee', 'bar', 'BETA') ('BETA', 'foo', 'ZETA', 'bar', 'bee') ('BETA', 'foo', 'ZETA', 'bar', 'BETA') 
+3
source

Itertools.product can help you here. In your example, you have a binary choice for three words in your string. So

 itertools.product((0, 1), repeat=3) 

will give you 8 possible replacements for bees and zee, where 0 means they do not replace, and 1 means replace with BETA and ZETA respectively.

The following does what you want.

 #!python3 import itertools map = { 'bee': 'BETA', 'zee': 'ZETA', 'dee': 'DELTA' } source_string = 'bee foo zee bar bee' products = [] for word in source_string.split(): if word in map: products.append((word, map[word])) else: products.append((word, )) for words in itertools.product(*products): print(' '.join(words)) 
+3
source

Source: https://habr.com/ru/post/944630/


All Articles