-5

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.

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
tslb14
  • 11
  • 3
  • 5
    Please edit your post to include an explanation of how `ARD` turns into each of those six strings – inspectorG4dget Oct 29 '15 at 21:15
  • 1
    use list(myString), then you can use itertools.combinations, http://stackoverflow.com/questions/8371887/making-all-possible-combinations-of-a-list-in-python – Chris Montanaro Oct 29 '15 at 21:28
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [MCVE](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. – Prune Oct 29 '15 at 21:46

2 Answers2

1

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']
stanleyli
  • 1,427
  • 1
  • 11
  • 28
-1

Thanks to @stanleyli for mind-reading the OP.

>>> map(''.join, itertools.product(*map(myDict.get, myString)))
['AAA', 'AAT', 'AAG', 'AGA', 'AGT', 'AGG']
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107