简体   繁体   中英

How to find possible combinations of a string by substituting characters in the string using a dictionary?

I'm trying to find all possible combinations of a string while substituting some characters in the string using a dictionary. I have to accomplish this goal without importing any modules. Here is an example:

myDict = {'R':'AG', 'Y':'CT', 'M':'CA', 'G':'G', 'D':'ATG', 'A':'A'}

myString = "ARD"

So I want to write out all the possible combinations of myString using the above dictionary which should be "AAA","AAT","AAG","AGA","AGT","AGG"

I can't figure out how to iterate for each characters in the string and then put them in a list or something.

IMO OP's description is a little bit vague but clear enough.

it sounds like a simple interview question to test the skill of recursion. See the answer (assume no duplication in myDict 's values)

results = []
def recr(str, pos):
    for w in myDict[myString[pos]]:
        if len(myString) - 1 == pos:
            results.append(str + w)
        else:
            recr(str + w, pos + 1)
recr('', 0)
print results

Screen output:

['AAA', 'AAT', 'AAG', 'AGA', 'AGT', 'AGG']

Thanks to @stanleyli for mind-reading the OP.

>>> map(''.join, itertools.product(*map(myDict.get, myString)))
['AAA', 'AAT', 'AAG', 'AGA', 'AGT', 'AGG']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM