python - Get ALL results of a word mapping with a dictionary -


i got word this: kfc

then dictionary: {'k':'1', 'c':'3'}

how can list that?

kfc, 1fc, kf3, 1f3

it means there 2^n possibilities, n number of dictionary's keys in word.

p/s: can think using recursive function, however, prefer non-recursive.

you can use itertools.product. example, let's define preliminaries:

>>> import itertools >>> s = 'kfc' >>> d = {'k':'1', 'c':'3'} 

now, let's compute result:

>>> [ ''.join(x) x in itertools.product( *[(c, d.get(c)) if d.get(c) else c c in s] ) ] ['kfc', 'kf3', '1fc', '1f3'] 

how works

first, use list comprehension posibilities need consider:

>>> [(c, d.get(c)) if d.get(c) else c c in s] [('k', '1'), 'f', ('c', '3')] 

in above list comprehension, iterate through each character c in string s. each c, assemble possibilities either (c, d[c]) if d[c] exists or else c if doesn't.

next, use itertools create possible products:

>>> list( itertools.product( *[(c, d.get(c)) if d.get(c) else c c in s] ) ) [('k', 'f', 'c'), ('k', 'f', '3'), ('1', 'f', 'c'), ('1', 'f', '3')] 

the above has answers need. need re-assemble strings using ''.join:

>>> [ ''.join(x) x in itertools.product( *[(c, d.get(c)) if d.get(c) else c c in s] ) ] ['kfc', 'kf3', '1fc', '1f3'] 

Comments